JSON Tutorial – Introduction, Structure, Syntax Rules, and Data Exchange
In this tutorial, we’ll introduce the JSON data exchange format. This post covers a JSON object’s structure, JSON syntax rules, data exchange with JSON, and programming languages support for JSON.
What is JSON?
- JSON is a lightweight, human-readable data-interchange format.
- JSON is used to store a collection of name-value pairs or an ordered list of values.
- JSON is useful for serializing objects, and arrays for transmitting over the network.
- JSON is very easy to parse and generate and doesn’t use a full markup structure like an XML.
- JSON became a popular alternative of XML format for its fast asynchronous client–server communication.
- All JSON files have the extension
.json
.
Structure of a JSON Object:
A JSON can be:
- A collection of name-value pairs:
The name must be a double-quoted string; and the value can be another string, an array, a number, boolean or null. The value itself can be another JSON object.
- An ordered collection:
JSON can be used to store an ordered collection of objects/values. The collection is similar to an array of primitives and array of objects in programming languages.
JSON Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
{ "firstName": "John", "lastName": "Snow", "age": 25, "children": [], "spouse": null, "address": { "street": "7504 Taylor Drive", "city": "New York City", "state": "New York", "postalCode": "11238" }, "phoneNumbers": [ { "type": "mobile", "number": "212 555-3346" }, { "type": "fax", "number": "646 555-4567" } ] } |
In the above example,
- The first two name-value pairs maps a string to another string.
- The third name-value pair maps a string
age
with a number 25. - The fourth name-value pair maps a string
children
with an empty array[]
. - The fifth name-value pair maps a string
spouse
with anull
value. - The sixth name-value pair maps a string
address
with another JSON object. - The seventh name-value pair maps a string
phoneNumbers
with an array of JSON objects.
JSON Syntax Rules:
- A JSON object is surrounded by curly braces
{}
. - The name-value pairs are grouped by a colon
(:)
and separated by a comma(,)
. - An array begins with a left bracket and ends with a right bracket
[]
. - The trailing commas and leading zeros in a number are prohibited.
- The octal and hexadecimal formats are not permitted.
- Each key within the JSON should be unique and should be enclosed within the double-quotes.
- The boolean type matches only two special values:
true
andfalse
and NULL values are represented by thenull
literal (without quotes).
JavaScript JSON built-in library:
JavaScript JSON built-in library provides two functions to decode and encode JSON objects – JSON.parse()
and JSON.stringify()
.
1. JSON.stringify()
returns a JSON string corresponding to a JavaScript object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<!DOCTYPE html> <html> <head> <title>Encoding a JavaScript object into a JSON string.</title> </head> <body> <div id="json"></div> <script> var obj = { "fruit": "Apple", "types": ["Small", "Medium", "Large"], "quantity": 1000 }; var json_string = JSON.stringify(obj); document.getElementById("json").innerHTML = json_string; </script> </body> </html> |
Output:
{“fruit”:”Apple”,
“types”:[“Small”,”Medium”,”Large”],
“quantity”:1000}
2. JSON.parse()
is a safe and fast method of decoding a JSON string as JavaScript object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<!DOCTYPE html> <html> <body> <h2>Decoding a JSON string into a JavaScript object.</h2> <div id="json"></div> <script> var json_str = '{"fruit":"Apple","types":["Small","Medium","Large"],"quantity":1000}'; try { var obj = JSON.parse(json_string); document.getElementById("json").innerHTML = obj.fruit + ", [" + obj.types + "], " + obj.quantity; } catch (e) { alert("Cannot parse given string"); } </script> </body> </html> |
Output:
Apple,
[Small,Medium,Large],
1000
We can also parse a JSON string into a JavaScript object by invoking the eval()
function on the JSON string wrapped by parenthesis. This works since JSON is derived from JavaScript. eval()
is an evil function, which should be avoided at all costs. This is because eval
can execute any malicious scripts on the user’s machine with the caller’s privileges. Moreover, malicious code can find the scope in which eval()
was invoked, making the website vulnerable to attacks. JSON.parse()
is the safe and fast alternative of eval, which safely fails on malicious code. JSON is included in almost all modern browsers. For old versions of browsers, use an external JavaScript library such as Douglas Crockford’s json2.js.
Data Exchange with JSON:
JSON is primarily used for the transmission of serialized text between a browser and a server.
- Sending Data:
In client-side, the JavaScript object is first converted to into a JSON string using
JSON.stringify()
method. And the resultant string is then transmitted to a server in the request body or param. - Receiving Data:
The server might return another JSON string as the response. Any JSON received from the server can be converted into JavaScript objects using the
JSON.parse()
method.
The official Media type for JSON is application/json
.
Programming Languages Support:
Originally, JSON was intended to be a subset of the JavaScript languages, but now almost all major programming languages support JSON due to its language-independent data format. JSON’s official website lists major JSON libraries available in various programming languages which can be used to parse and generate JSON. For instance, the most popular JSON libraries for Java are GSON, JSON.simple, Jackson, and JSONP.
That’s all about JSON data exchange format.
Useful links:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)