简体   繁体   中英

Serializing/Deserializing JSON?

I'm new to using ION so please excuse the probably simple question. In looking at the one of the cookbook samples provided in the documentation ...

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

Can ION take in a JSON object as opposed to a string? Doing something like the below where I change the unformatted variable from a string to a JSON object results in zero bytes from the writer...

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

Yes, object = JSON.parse(string) and string = JSON.stringify(object) is what you are looking for. However your JSON is malformed in the example, and should not use variables:

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

Assuming a = 1, b = 2, c = 3, for example, if you mean texts a, b, c, then:

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

Once made this:

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

and

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

Are equivalent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM