2 回答
TA贡献1895条经验 获得超3个赞
对于数组,对项目采用递归方法。
const
json_encode = (input) => {
if (typeof input === "string") return `"${input}"`;
if (typeof input === "number") return `${input}`;
if (Array.isArray(input)) return `[${input.map(json_encode)}]`;
};
console.log(json_encode([1, 'foo', [2, 3]]));
console.log(JSON.parse(json_encode([1, 'foo', [2, 3]])));
TA贡献1828条经验 获得超6个赞
您已经拥有将标量值转换为 json 值的函数。
因此,您可以为所有数组成员调用此函数(例如,使用https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/map)然后加入它(https://developer .mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/join)并将'['和']'添加到结果字符串
PS:这种方法也适用于您拥有数组数组的情况
实现示例:
var my_json_encode = function(input) {
if(typeof(input) === "string"){
return '"'+input+'"'
}
if(typeof(input) === "number"){
return `${input}`
}
if(Array.isArray(input)) {
const formatedArrayMembers = input.map(value => my_json_encode(value)).join(',');
return `[${formatedArrayMembers}]`;
}
}
添加回答
举报
