JSON Explanation
JSON Explanation
This is an object with 3 properties, name, age, car, with each property having a value
Language independent
You can parse the JSON string with a JS program and access the data as an object:
JSON.parse()
JSON.stringify()
JSON makes it possible to store JS objects as text, and text is always one of the legal formats.
JSON Syntax
Rules:
Name/value pair consists of a field name (in double quotes) followed by a colon, followed by a value:
“Name”:”John”
JSON-Evaluates to JS objects
JSON
{“name”:”John”}
JavaScript
{name:”John”}
a string
a number
an object
an array
a boolean
null
In JavaScript values can be all of the above, plus any other valid JavaScript expression, including:
a function
a date
undefined
{
"employee":{"name":"John", "age":30, "city":"New York"}
}
arrays
{
"employees":["John", "Anna", "Peter"]
}
Booleans
{"sale":true}
Null
{"middlename":null}
When receiving data from a web server, the data is always a string.
Parse the data with JSON.parse(), and the data becomes a JavaScript
object.
Use the JavaScript function JSON.parse() to convert text into a JavaScript object:
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = obj.name;
</script>
A JSON value cannot be a date, it must be stored as a string and then convert to a
date after
JSON cannot be a function, make it as a string and parse it and convert it back
later. (But avoid using them as they will lose their scope and you’ll have to revert
them back later using eval().)
JSON.stringify()