Serializing/Deserializing JSON?

515 Views Asked by At

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

There are 1 best solutions below

4
On

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.