JSON is a data format.
It is easy for humans to edit / write & computers to parse / generate.
A common use of JSON is to exchange data to/from a web server.
Example library in JSON:
{
"myBooks": [
{
"title" : "cloudy with a chance of meatballs",
"type": "kids"
},
{
"title" : "if hemingway wrote javascript",
"type": "code"
}
]
}
JSON is formatted like a Javascript object literal.
Property names and strings must be enclosed in double quotation marks.
Property values can be arrays or nested objects. Values can be numbers, booleans, null and undefined.
Property names and values are separated by a :colon to form name:value pair
A comma-separted list of name:value pairs is enclosed within {} braces to create a complete JavaSCript object.
JSON data is transferred as text so you MUST convert JSON to objects / arrays that can be used in a JavaScript Program
The key to working with JSON is to convert it from a string to an object using the JSON.parse
method.
Then you can access the properties or elements in the data using dot / bracket notation.
{
"title" : "cloudy with a chance of meatballs",
"type": "kids"
}
var book = JSON.parse(response);
book.title; // cloudy with a chance of meatballs
book.type; // kids
https://www.w3schools.com/js/js_json_stringify.asp
When sending data to a web server, the data has to be a string. Convert a JavaScript object into a string with JSON.stringify().
Javascript Object
var obj = { "name":"John", "age":30, "city":"New York"};
Use the JavaScript function JSON.stringify() to convert it into a string.
var myJSON = JSON.stringify(obj);
The result will be a string following the JSON notation.
var obj = { "name":"John", "age":30, "city":"New York"};
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON; //{"name":"John","age":30,"city":"New York"}