0

我是使用 ION 的新手,所以请原谅这个可能很简单的问题。在查看文档中提供的食谱样本之一...

let ion = require('ion-js');

let unformatted = '{level1: {level2: {level3: "foo"}, x: 2}, y: [a,b,c]}';

let reader = ion.makeReader(unformatted);
let writer = ion.makePrettyWriter();
writer.writeValues(reader);
writer.close();
console.log(String.fromCharCode.apply(null, writer.getBytes()));

ION 可以接收 JSON 对象而不是字符串吗?执行类似下面的操作,我将未格式化的变量从字符串更改为 JSON 对象,导致写入器的字节为零......

let ion = require('ion-js');

let unformatted = {level1: {level2: {level3: "foo"}, x: 2}, y: [a,b,c]};

let reader = ion.makeReader(unformatted);
let writer = ion.makePrettyWriter();
writer.writeValues(reader);
writer.close();
console.log(String.fromCharCode.apply(null, writer.getBytes()));
4

1 回答 1

0

是的,object = JSON.parse(string) 和 string = JSON.stringify(object) 就是您要找的。但是,您的 JSON 在示例中格式不正确,不应使用变量:

{"level1":{"level2":{"level3":"foo"},"x":2},"y":[1,2,3]}

假设 a = 1, b = 2, c = 3,例如,如果您的意思是文本 a、b、c,那么:

{"level1":{"level2":{"level3":"foo"},"x":2},"y":["a","b","c"]}

一旦做到这一点:

JSON.stringify({"level1":{"level2":{"level3":"foo"},"x":2},"y":["a","b","c"]});

JSON.stringify(JSON.parse("{\"level1\":{\"level2\":{\"level3\":\"foo\"},\"x\":2},\"y\":[\"a\",\"b\",\"c\"]}"));

是等价的。

于 2020-01-10T11:54:21.493 回答