JavaScript Object Notation or JSON
is a way to represent JavaScript objects
as strings.
This enables us to send our data
across to different devices on the internet
which could be using different programming languages.
JavaScript has in-built functions
to convert an object to JSON - JSON.stringify()
.
When we pass an object to JSON.stringify()
,
it returns the JSON representation
of that object.
We'll learn more about this method
in the next chapter.
Let's start out simple
and
convert an empty object to JSON.
In the above example,
JSON.stringify
returns a string
that only contains {}
.
This represent an empty object.
Now let's convert an object
with one property into JSON.
In the above example,
we get a string that is very similar
to the object definition
{ name: "Sam" }
.
The only difference is that
the key is wrapped in double quotes
in the JSON string.
All keys in a JSON string
will be wrapped in double-quotes.
Now, let's add another property.
This time with a number value.
In the above example,
the output is a comma-separated
list of key-value pairs.
Only string values in a JSON string
are wrapped in double-quotes.
Since the value of user.age
is a number,
it is not wrapped in double-quotes
in the JSON string.
Here are some more examples
of JSON representations
of various data types in JavaScript.
Do note that,
null
, Infinity
and NaN
will be represented as "null"
in JSON strings.
undefined
and functions
will just return undefined
when passed to JSON.stringify
.
We can see the difference between
null
and undefined
in JSON strings.
While JSON.stringify(null)
returns
a string "null"
,
JSON.stringify(undefined)
simply returns undefined
.
Any undefined value is also
omitted from JSON strings.
In the above example,
the property of nullAndUndefined
with the value null
shows up in the JSON string.
But the property of nullAndUndefined
with the value undefined
does not show up in the JSON string.