Hi everyone, and welcome to another exciting edition of Boring JavaScript. In this edition, we tackling the JSON methods.
Don’t want to read? Then watch the video!
Notating the Objects
JSON is an acronym for “JavaScript Object Notation”, and it’s a way to take ordinary JavaScript objects and convert them to strings (or to take the string and covert it into objects). This is very useful for transmitting data from one application to another (even in a different language), and for communications over the ‘Net in general, like REST APIs.
Using JSON is very easy. As a static class within JavaScript, you simply call it along with the method you wish to invoke, and pass to it as an argument the object you wish to convert.
And that’s it! So let’s take a look at the two main methods, ‘parse’ and ‘stringify’.
Wikipedia has a great write-up on JSON, with links to all the specifications.
Out, out, accursed Spot!
To covert an object to a string – as we said, perfect for sending Object data over a wire – all you need to do is call the ‘stringify’ method.
const myCat = {
name: "Fluffy",
alive: true,
stats: {
height: .398,
weight: 6.12,
claws: true
}
}
const myCatInJSON = JSON.stringify(myCat);
console.log(myCatInJSON);
/* displays:
{"name":"Fluffy","alive":true,"stats":{"height":0.398,"weight":6.12,"claws":true}}
*/
Line 11 shows you how to call the JSON.stringify() method. It will convert your object to a string that can then be transmitted over wires, read by other applications (and languages), and basically allow you share you object with just about any person or application on the planet (even Mars).
And not just objects – arrays work to!
const animals = [
"Cat", "Dog", "Horse", "Cow", "Coyote", "Road Runner", "Dolphin", "Whale", "Lizard"
];
console.log(JSON.stringify(animals));
/* displays:
["Cat","Dog","Horse","Cow","Coyote","Road Runner","Dolphin","Whale","Lizard"]
*/
And that’s all there is to it.
But what about the other way? What if you were given a JSON string and needed to convert it into an object. That’s simple, too.
Parse that Syntax
To convert a JSON string into an object, you use the JSON.parse() method. It takes one argument – the JSON string – and it will convert it a JavaScript object that you can use.
Let’s reverse the above code and see what happens.
const JSONString = `{"name":"Fluffy","alive":true,"stats":{"height":0.398,"weight":6.12,"claws":true}}`;
const myCat = JSON.parse(JSONString);
console.log(myCat);
/* displays:
{
name: 'Fluffy',
alive: true,
stats: { height: 0.398, weight: 6.12, claws: true }
}
*/
And that’s it! Nothing could be easier.
What happens if the format of the JSON string is bad? (Note: I’ve removed the quotes around the ‘alive’ word in the string below – that’s invalid JSON syntax):
const JSONString = `{"name":"Fluffy",alive:true,"stats":{"height":0.398,"weight":6.12,"claws":true}}`;
const myCat = JSON.parse(JSONString);
console.log(myCat);
/* displays:
SyntaxError: Unexpected token a in JSON at position 17
at JSON.parse (<anonymous>)
... stack dump follows
*/
Yes, that’s right – the JSON.parse will even detect if the format of the JSON string is invalid, and throw an exception. All you have to do is pop a try/catch around the JSON.parse() code and handle that error.
To much of Anything is Not Good
There is a caveat I need to warn you about: Many objects will have recursive object pointers within them, and that can cause problems with JSON.parse() or JSON.stringify().
For example, an HTMLElement (the JavaScript object behind an HTML tag) will have a collection of child elements defined. Each of those child elements will also have a pointer back to the parent element. When JSON looks at this object, it will go into the each child element, then go back to the parent element, then parse the child elements again, then back to the parent element, and then … you get the picture. Recursive parsing for the rest of eternity (or until the memory runs out on your computer).
Let’s take a look at this example:
class Cat {
constructor(parentCat = null) {
this.children = [];
this.parent = parentCat;
if (parentCat) {
parentCat.addCat(this);
}
}
addCat (cat) {
this.children.push(cat);
}
}
const myCat = new Cat();
const myKitten1 = new Cat(myCat);
const myKitten2 = new Cat(myCat);
const myKitten3 = new Cat(myCat);
console.log(JSON.stringify(myCat));
/* displays:
TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Cat'
| property 'children' -> object with constructor 'Array'
| index 0 -> object with constructor 'Cat'
--- property 'parent' closes the circle
at JSON.stringify (<anonymous>)
*/
In the example above, each cat can have children, and it will have a pointer to it’s parent cat (passed as an argument to the constructor). This will give us a ‘recursive’ object. If you start with the parent cat (‘myCat’), then look at each of the three children, you will see that each child points back to the parent cat through the ‘parent’ property. If you were a parser, and you encountered a child with a parent, you would then go back to the parent and start parsing it again – which means you will also start parsing each child, which in turn parses the parent again, and so on and so forth. As you can see, this will create a problem.
Luckily for us, JSON has mechanisms within it to detect recursive properties of an object, and will throw an exception if it detects a recursive object.
Bottom line: Don’t use JSON.stringify() on recursive objects.
The Video
As always, here is our Boring JavaScript video on the above topic.
Shameless Plug
And make sure to check us out on the web!
Categories: Boring JavaScript Javascript
thevirtuoid
Web Tinkerer. No, not like Tinkerbell.
Creator of the game Virtuoid. Boring JavaScript. Visit us at thevirtuoid.com
Leave a Reply