JSON – Introduction
JavaScript object notation
‘{“name”: “John”, “age”:30, “car”:null}’
This is an object with 3 properties, name, age, car, with each property having a value
JSON is a lightweight data-interchange format
Plain text written in JS object notation
Used to send data between computers
Language independent
You can parse the JSON string with a JS program and access the data as an object:
Let personName = obj.name;
Let personage = obj.age;
JS has a fxn for JSON string => JS object
JSON.parse()
Object into JSON string =>
JSON.stringify()
JSON makes it possible to store JS objects as text, and text is always one of the legal formats.
JSON Syntax
Rules:
- data in name/value pairs
- data separated by commas
- curly braces hold objects
- square brackets hold arrays
JSON data- a name and a value
JSON names require double quotes
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 format is almost identical to JS objects
-in JSON, keys must be strings, written with double quotes:
JSON
{“name”:”John”}
In JS, keys can be strings, numbers or identifier names:
JavaScript
{name:”John”}
In JSON, values must be one of the following data types:
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
JSON numbers must be an int or a float
Values in JSON can be objects
{
"employee":{"name":"John", "age":30, "city":"New York"}
}
arrays
{
"employees":["John", "Anna", "Peter"]
}
Booleans
{"sale":true}
Null
{"middlename":null}
A common use of JSON is to exchange data to/from a web server.
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.
Example - Parsing JSON
Imagine we received this text from a web server:
'{"name":"John", "age":30, "city":"New York"}'
Use the JavaScript function JSON.parse() to convert text into a JavaScript object:
const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');
use the object in your page
<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()
Sending data to a web server requires it to be a string (aka sending text).
Convert your JS object into a string with JSON.stringify()
const obj = {name: "John", age: 30, city: "New York"};
convert to string using JS fxn
const myJSONstring = JSON.stringify(obj);