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

问题描述 投票:0回答:1

我想写一个函数,接受一些对象,例如一个数字、一个字符串、一个列表或一个映射(键值对);并将输入的有效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)来改变它,但我不想使用它。我知道我可以创建一些递归的解决方案,因为我已经为数字和字符串设置了基例。我在这个问题上受阻,任何帮助都将是感激的

编辑:所以解决方案,因为已经在下面的答案部分提供了! 谢谢 :)

javascript arrays json javascript-objects
1个回答
1
投票

对于数组采取递归的方式处理项目。

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

1
投票

你已经有了将标量值转换为json值的函数。

所以,你可以为所有数组的成员调用这个函数(例如,使用 https:/developer.mozilla.orgrudocsWebJavaScriptReferenceGlobal_ObjectsArraymap。),然后加入它(https:/developer.mozilla.orgrudocsWebJavaScriptReferenceGlobal_ObjectsArrayjoin。),并在生成的字符串中添加'['和']'。

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}]`;
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.