1. js 将json数据转化为?&的形式
将JSON数据转化为?&的形式”(将JSON数据转换为?&格式)。“?&格式”几乎肯定是指查询字符串格式(key1=value1&key2=value2),通常前面会带一个?(例如,?foo=bar&baz=qux)。
在 JavaScript 中,将 JSON(对象)转化为 ?key=value&key2=value2 这种形式(即 URL Query String,查询字符串)。
1.1. 手写递归函数(处理深层嵌套对象)
如果 JSON 里有嵌套对象或数组(比如 { user: { id: 1 } }),URLSearchParams 处理得不够直观(会变成 [object Object])。这时可以使用递归函数,将其转化为 user[id]=1 或 tags[]=1&tags[]=2 的格式。
function jsonToQueryString(obj, prefix = null) {
const pairs = [];
for (const key in obj) {
if (!obj.hasOwnProperty(key)) continue;
const value = obj[key];
const fullKey = prefix ? `${prefix}[${key}]` : key; // 生成 user[id] 这种格式
// 处理 null 和 undefined(跳过或置空)
if (value === null || value === undefined) {
continue;
}
// 递归处理嵌套对象
if (typeof value === 'object' && !Array.isArray(value)) {
pairs.push(jsonToQueryString(value, fullKey));
}
// 处理数组(PHP常见风格: tags[]=1&tags[]=2 )
else if (Array.isArray(value)) {
for (const item of value) {
pairs.push(`${fullKey}[]=${encodeURIComponent(item)}`);
}
}
// 处理基本类型
else {
pairs.push(`${fullKey}=${encodeURIComponent(value)}`);
}
}
return pairs.join('&');
}
// 使用示例
const data = {
user: { id: 1, name: 'Alex' },
interests: ['coding', 'music']
};
const str = jsonToQueryString(data);
console.log('?' + str);
// 输出: ?user[id]=1&user[name]=Alex&interests[]=coding&interests[]=music
优点:有嵌套对象/数组,不想引入库。使用上面的 手写递归函数(注意后端接受格式,如 user[id] 或 user.id)。
注意:拼接到 URL 时,如果原本 URL 已有 ?,请使用 & 连接,否则直接用 ? 拼接。所有值建议经过 encodeURIComponent 编码(上述方法均已自动处理)。
1.2. Vue封装
//src/helper/initHelper
/**
* json数据转化成?&地址参数形式
*/
const jsonToParam = (obj, prefix = null) => {
const pairs = [];
for (const key in obj) {
if (!obj.hasOwnProperty(key)) continue;
const value = obj[key];
// 生成 user[id] 这种格式
const fullKey = prefix ? `${prefix}[${key}]` : key;
// 处理 null 和 undefined(跳过或置空)
if (value === null || value === undefined) {
continue;
}
// 递归处理嵌套对象
if (typeof value === 'object' && !Array.isArray(value)) {
pairs.push(jsonToQueryString(value, fullKey));
}
// 处理数组(PHP常见风格: tags[]=1&tags[]=2 )
else if (Array.isArray(value)) {
for (const item of value) {
pairs.push(`${fullKey}[]=${encodeURIComponent(item)}`);
}
}
// 处理基本类型
else {
pairs.push(`${fullKey}=${encodeURIComponent(value)}`);
}
}
return "?"+pairs.join('&');
}
export default {
jsonToParam: jsonToParam,
}
//使用
let paramObj = {}
paramObj.username = "admin"
paramObj.password = "admin123"
let param= initHelper.jsonToParam(paramObj);
4万+

被折叠的 条评论
为什么被折叠?



