为了账号安全,请及时绑定邮箱和手机立即绑定

在不使用 JSON.stringify 的情况下将数组转换为有效的 JSON 字符串?

在不使用 JSON.stringify 的情况下将数组转换为有效的 JSON 字符串?

慕容708150 2022-07-21 10:15:26
我正在尝试编写一个接受一些对象的函数,例如一个数字、一个字符串、一个列表或一个映射(键值对);并将该输入的有效 JSON 表示形式作为字符串返回。我已经为简单的数字和字符串输入设置了其他 json 编码器:Input => Output a number with value 123 => 123 (string)a string with value abc => "abc" (string)但我在转换数组时遇到问题,例如 [1,"2",3]Input => Output 1,2,three array => [1,2,"three"] (string) 这是我当前的代码:var my_json_encode = function(input) {  if(typeof(input) === "string"){      return '"'+input+'"'  }  if(typeof(input) === "number"){      return `${input}`  }  //This is causing my issue  if(Array.isArray(input)) {      console.log(input)  }我可以简单地添加并返回 JSON.stringify(input) 来更改它,但我不想使用它。我知道我可以创建某种递归解决方案,因为我为数字和字符串设置了基本案例。我被阻止了,任何帮助将不胜感激编辑:所以答案部分提供了下面的解决方案!谢谢 :)
查看完整描述

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]])));


查看完整回答
反对 回复 2022-07-21
?
30秒到达战场

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}]`;

   }

}


查看完整回答
反对 回复 2022-07-21
  • 2 回答
  • 0 关注
  • 168 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号