In the older days, we send packets of data across the network using XML like so:
1 2 3 4 |
<object> <firstname>rick</firstname> <lastname>cao</lastname> </object> |
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.
1 2 3 4 5 6 |
let obj = { name: 'mary', isProgrammer: true } console.log(JSON.stringify(obj)); |
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.
1 2 3 4 |
JSON.parse('{ "name": "mary", "isProgrammer": true } |