JSON and object literals

In the older days, we send packets of data across the network using XML like so:

The issue here is that our tags ‘firstname’ takes up too many characters. For one piece of data, we’re sending a property name twice.

Then they looked at how JS does its key/value convention and adopted that because it saves space.

Hence, nowadays, we send packets via JSON.

However, there are rules for JSON: property needs to be wrapped in quotes

JS does come with built-in function JSON.stringify.

JSON.stringify will convert any JS object into a JSON string.

And if we have a JSON string, we can use JSON.parse() and convert it into a JS object.

output


{ "name": "mary", "isProgrammer": true }

typeof JSON.stringify(obj) will give you “String”.

If we were to parse JSON string into a JS object, we first have to make sure its valid JSON.
Make sure you put quotes around the properties and make the whole thing into a string.


{name: “mary”, isProgrammer: true}