30 Days Of JavaScript

Day 14: Strings and JSON

Lesson 6: JSON.stringify & JSON.parse

JSON.stringify()

The first is JSON.stringify(), this takes a JavaScript objects and creates a stringified version of it that adheres to the JSON standard.

You'll notice that looks pretty awful BUT it has all the keys/properties in double quotes.

If you want to make it look nicer, there are some optional arguments you can pass in to it. The full declaration is:

1JSON.stringify(value, replacer, space);

Don't worry about replacer we can just set that to null. The space argument however is pretty useful, it sets the number of spaces to indent sub properties. This is purely to make things more humanly readable, however if you do intend to read the contents of the file you write this to, then it is super useful.

It won't work in the playground though sadly ☹️

JSON.parse()

If you read JSON data from somewhere (99% of the time this will be from a file or in the response of URL API request) then you can do so with JSON.parse().

And there you have it, how to convert JavaScript data into a string and back again using the JSON API.

We spoke a long time ago about value type versus reference type. Remember that objects are really reference to a place in memory, where as numbers and strings etc are actually the value you set them to.

So, if you want to copy an object doing this:

1const car = {
2  make: "Nissan",
3  model: "GTR",
4  transmission: "manual",
5  familyFriendly: false,
6  gears: 6,
7};
8
9const newCar = car;

Doesn't create a new car. It creates a new reference to the same object. If you do newCar.gears = 7 then it will change on both car and newCar because you modified the same location in memory.

If you really complete copy of car then you can do this:

1const newCar = JSON.parse(JSON.stringify(car));

Can you think why this works?

Well JSON.stringify() returns a string. A string a value type. So it's not pointing at car in memory, it has all the data of car in it. Then we JSON.parse() it and get a new object.

Now doing newCar.gears = 7 will only affect newCar because it's what's called a Deep Copy of car.

Outline

Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co