将数组转换为有效的JSON字符串而不使用JSON.stringify? [英] Converting array to valid JSON string without using JSON.stringify?

查看:239
本文介绍了将数组转换为有效的JSON字符串而不使用JSON.stringify?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数,该函数带有一些对象,例如数字,字符串,列表或映射(键-值对);并以字符串形式返回该输入的有效JSON表示形式。

I'm trying to write a function that takes some object, for example a number, a string, a list, or a map (of key-value pairs); and returns a valid JSON representation of that input as a string.

我已经为简单的数字和字符串输入设置了其他json编码器:

I have already set up other json encoders for simple numbers and string inputs:

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)进行更改,但我不想使用它。
我知道我可以创建某种递归解决方案,因为我已经为数字和字符串设置了基本案例。我在此方面受阻,将不胜感激

I could simply add and return JSON.stringify(input) to change it but I don't want to use that. I know I can create some sort recursive solution as I have base cases set up for numbers and strings. I'm blocked on this and any help will be appreciated

编辑:因此,下面答案部分提供的解决方案!谢谢:)

推荐答案

对于数组,使用递归方法处理项。

For arrays take a recursive approach with the items.

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

这篇关于将数组转换为有效的JSON字符串而不使用JSON.stringify?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆