JSON Syntax
JSON format is like a part of JavaScript format.
JSON Syntax Rules
JSON syntax comes from how JavaScript represents objects.
- Data consists of pairs of names and values.
- Data gets divided using commas.
- Curly braces contain objects.
- Square brackets are used to contain arrays.
JSON Data - A Name and a Value
JSON data is written as pairs of names and values, also known as key/value pairs.
A name and its value are like a pair. The name is in double quotes, followed by a colon, and then the value.
Example
"name":"John"
JSON keys need to be enclosed in double quotes.
JSON - Evaluates to JavaScript Objects
The JSON format looks a lot like JavaScript objects.
In JSON, thekeys need to be written as strings using double quotes.
JSON
{"name":"John"}
In JavaScript, keys can be different types like strings, numbers, or identifier names.
JavaScript
{name:"John"}
JSON Values
In JSON, values need to be one of these data types:
- a string
- a number
- an object
- an array
- a boolean
- null
In JavaScript, values can be anything mentioned earlier, as well as any other valid expression in JavaScript, such as:
- a function
- a date
- undefined
In JSON, you need to use double quotes when writing string values.
JSON
{"name":"John"}
In JavaScript, you can use either double or single quotes to write string values.
JavaScript
{name:'John'}
JavaScript Objects
JSON is easy to work with in JavaScript because its syntax is based on JavaScript object notation. You don't need much extra software to handle JSON in JavaScript.
You can use JavaScript to make an object and give it data, like this:
Example
person = {name:"John", age:31, city:"New York"};
To get into a JavaScript object, you do it like this:
You can access it in this way too:
You can change data using this method:
It can be changed in this way too:
In this tutorial, you'll discover how to change JavaScript objects into JSON format at a later point.
JavaScript Arrays as JSON
JavaScript arrays can be expressed as JSON, similar to how JavaScript objects are written in JSON format.
Later in this tutorial, you'll discover more about objects and arrays.
JSON Files
- The format used for JSON files is ".json".
- The type for JSON text is "application/json".