JSON Object v. JavaScript Object
Recently in my job search, I had an interview and was asked what I deemed to be an interesting interview question. So, I decided I wanted to open the book wider on the topic!
Interviewer’s Question: “What is the difference between a JSON object and a Javascript object?”
What is JSON?
First off, it stands for JavaScript Object Notation. JSON syntax is derived from Javascript objects, but the JSON format is text only, meaning a JSON object is quite literally just a string.
See in this code example what JSON object looks like:
Many times you’ll find a JSON object written as a string with a key/value pair. See “firstName” is the key pointing to Harry.
When do we use a JSON object?
JSON is used to read data from a web server and then display that data onto a webpage. When we exchange data between a browser and a server it can only be text, hence we can use JSON for this.
Now is when we get our JavaScript object cooking!
We want to read a JSON object (essentially our string of data) and convert it into a JavaScript Object. The best way to do this is to use this built-in JavaScript function JSON.parse().
Methods to convert JSON.
Receiving Data
JSON.parse() will convert text into a JavaScript object.
On the flip side, we also want to use JSON to convert our JavaScript object into JSON so that the data can be sent to a web server and read.
Sending Data
JSON.stringify() will convert a JavaScript object into a JSON object that can then be sent to a web server.
JavaScript object vs. JSON object syntax
A Javascript object has a similar syntax to JSON, it uses curly braces and key/value pairs.
The main difference in syntax is that in a JSON object the keys must be a string written with double quotes.
In JavaScript, a key can be strings, numbers, or identifier names, and the strings can be written in single or double quotes.
JSON Data Types
When sending our JSON text it must have a valid JSON data type, those include:
- A string
- A number
- An object (JSON object)
- An array
- A boolean
- Null
JSON values cannot be:
- A function
- A date
- undefined
Conclusion
Overall when comparing the two: a JSON object and a JavaScript object, we know that a JSON object is the messenger. JSON is written only as text and is a seamless way to send Javascript data between the browser and server. We will convert the Javascript object by using JSON.parse() to convert a JSON object back into a JavaScript object, and we will use JSON.stringify() to turn a JavaScript object into a string that is our JSON object.