-
JSON stands for JavaScript Object Notation
-
JSON is a lightweight data interchange format
-
JSON is language independent *
-
JSON is "self-describing" and easy to understand
* The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is text only. Code for reading and generating JSON data can be written in any programming language.
This JSON syntax defines an employees object: an array of 3 employee records (objects):
{
"employees": [
{ "firstName": "John", "lastName": "Doe" },
{ "firstName": "Anna", "lastName": "Smith" },
{ "firstName": "Peter", "lastName": "Jones" },
{ "firstName": "Mary", "lastName": "Williams" }
]
}In the example above, the object "employees" is an array. It contains three objects.
Each object is a record of a person (with a first name and a last name).
- The top level must be either an object or an array.
- An object begins with curly braces {}.
- A property name in double quotes "".
- Values are separated by commas , .
- Arrays begin with square brackets [].
- All values must be strings, numbers, booleans, nulls, objects, arrays, or undefined.
- Strings use single quotations ' '.
- Numbers do not need any separators.
- Boolean true/false values should always be lowercased.
- Null values should also be all lowercased.
- Objects may contain other objects inside them.
- Arrays can only have elements that are themselves objects or arrays.
- Comments start with // and extend until the end of line.
A common use of JSON is to read data from a web server, and display the data in a web page.
For simplicity, this can be demonstrated using a string as input.
First, create a JavaScript string containing JSON syntax:
let text = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';Then, use the JavaScript built-in function JSON.parse() to convert the string into a JavaScript object:
const obj = JSON.parse(text);let Data =
'{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';
const obj = JSON.parse(Data);
console.log(obj.employees[1].firstName + " " + obj.employees[1].lastName);
// Anna Smith