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

我正在尝试编写一个接受一些对象的函数,例如一个数字、一个字符串、一个列表或一个映射(键值对);并将该输入的有效 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) 来更改它,但我不想使用它。我知道我可以创建某种递归解决方案,因为我为数字和字符串设置了基本案例。我被阻止了,任何帮助将不胜感激


编辑:所以答案部分提供了下面的解决方案!谢谢 :)


慕容708150
浏览 170回答 2
2回答

蛊毒传说

对于数组,对项目采用递归方法。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]])));

30秒到达战场

您已经拥有将标量值转换为 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}]`;   }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript