What is Js Object Literal?
The standard definition would be: it is a comma-separated list of name-value pairs wrapped in curly braces. You can think of it as a 'container' for datas, for example:
const myObject = {
stringProp: 'value',
numberProp: 2,
booleanProp: false,
arrayProp: ["hello.jpg","smile.png"],
positionProp: {
x: 40,
y: 200
},
someAction: function(){
//action logics
}
};
What is JSON?
JSON stands for JavaScript Object Notation, which is a lightweight format for storing and transporting of data. Data is usually fetched from a server to the browser in this format. The syntax looks very similar to Js Objects.
In JSON format:
{
"firstName":"John",
"lastName":"Doe"
}
In JavaScript Object:
const person = {
firstName:"John",
lastName:"Doe"
}
Comparing to a JavaScript Object, the not-so-obvious difference is that both the name and value are doubled-quoted in JSON but only the value is doubled-quoted in Js Object.
Conversion
JavaScript has built-in support to convert between JSON and Js Object.
To convert an Object to JSON Data:
JSON.stringify(Object)
To convert a JSON data to an Object:
JSON.parse(data)
JavaScript Object will be displayed as the following on browser, thus the need to be converted to JSON.
[object Object]
For React users, sometimes we will forget to convert an Object to JSON and will often see this error message when we try to render it:
That's all! Thanks for reading my short post.
Top comments (0)