JavaScript JSON
JSON is a way to save and move data.
JSON is commonly employed when information is transmitted from a server to a webpage.
What is JSON?
- JSON is an acronym for JavaScript Object Notation.
- JSON is a simple way to exchange data in a computer-friendly format.
- JSON can be used with any programming language *.
- JSON is easy to understand because it describes itself.
The JSON syntax is based on the syntax used for JavaScript objects, but JSON itself is a text-only format. You can write code in any programming language to read and create JSON data.
JSON Example
This JSON structure describes an "employees" object, which is a collection of three employee records (objects):
JSON Example
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}
The JSON Format Evaluates to JavaScript Objects
The JSON format looks the same as the code used to create JavaScript objects.
Due to this similarity, a JavaScript program can effortlessly change JSON data into regular JavaScript objects.
JSON Syntax Rules
- Data is structured as name and value pairs.
- Data is divided by commas.
- Curly braces contain objects.
- Arrays are stored inside square brackets.
JSON Data - A Name and a Value
JSON data looks like name and value pairs, similar to properties in a JavaScript object.
A name/value pair is made up of a field name (enclosed in double quotes), followed by a colon, and then followed by a value.
JSON names must be enclosed in double quotes, while JavaScript names do not need this.
JSON Objects
JSON objects are placed within curly braces.
Similar to JavaScript, objects can hold several pairs of names and values.
JSON Arrays
JSON uses square brackets to enclose arrays.
Similar to JavaScript, an array can hold objects.
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
In the given example, there's a group called "employees," and it's like a collection of three things.
Every item represents a person and contains information about their first name and last name.
Converting a JSON Text to a JavaScript Object
JSON is often used to fetch information from a web server and show it on a webpage.
To make it simple, let's show this using a string as an input.
Start by making a string in JavaScript that has JSON syntax.
let text = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';
Next, utilize the JavaScript function JSON.parse()
to transform the string into a JavaScript object.
const obj = JSON.parse(text);
Lastly, incorporate the newly created JavaScript object into your webpage.
Learn more about JSON in our tutorial on JSON.