欧博娱乐A Beginner's Guide to JSON with Examples
A Beginner's Guide to JSON with Examples
September 04, 2019
In this article 👇
JSON — short for JavaScript Object Notation — is a popular format for storing and exchanging data. As the name suggests, JSON is derived from JavaScript but later embraced by other programming languages.
JSON file ends with a .json extension but not compulsory to store the JSON data in a file. You can define a JSON object or an array in JavaScript or HTML files.
In a nutshell, JSON is lightweight, human-readable, and needs less formatting, which makes it a good alternative to XML.
Syntax and Data TypesJSON data is stored as key-value pairs similar to JavaScript object properties, separated by commas, curly braces, and square brackets. A key-value pair consists of a key, called name (in double quotes), followed by a colon (:), followed by value (in double-quotes):
"name": "Atta"Multiple key-value pairs are separated by a comma:
"name": "Atta", "age": 30JSON keys are strings, always on the left of the colon, and must be wrapped in double quotes. Within each object, keys need to be unique and can contain whitespaces, as in "author name": "John Doe".
It is not recommended to use whitespaces in keys. It will make it difficult to access the key during programming. Instead, use an underscore in keys as in "author_name": "John Doe".
JSON values must be one of the following data types:
String
Number
Boolean (true or false)
Null
Object
Array
Note: Unlike JavaScript, JSON values cannot be a function, a date or undefined.
JSON StringsString values in JSON are a set of characters wrapped in double-quotes:
{ "firstName": "John", "lastName": "Doe" } JSON NumbersA number value in JSON must be an integer or a floating-point:
{ "age": 45, "weight": 75.5 } JSON BooleansBoolean values are simple true or false in JSON:
{ "admin": true } JSON NullNull values in JSON are empty words:
{ "middleName": null } JSON ObjectsJSON objects are wrapped in curly braces. Inside the object, we can list any number of key-value pairs, separated by commas:
{ "firstName": "John", "lastName": "Doe", "email": "john.doe@example.com", "age": 45, "weight": 67, "admin": true } JSON ArraysJSON arrays are wrapped in square brackets. Inside an array, we can declare any number of objects, separated by commas:
[ { "name": "Jason", "gender": "M", "age": 27 }, { "name": "Rosita", "gender": "F", "age": 23 }, { "name": "Leo", "gender": "M", "age": 19 } ]In the above JSON array, there are three objects. Each object is a record of a person (with name, gender, and age).
Nesting Objects & ArraysJSON can store nested objects and arrays as values assigned to keys. It is very helpful for storing different sets of data in one file:
{ "name": "Jason Ray", "profession": "Software Engineer", "age": 31, "address": { "city": "New York", "postalCode": 64780, "Country": "USA" }, "languages": ["Java", "Node.js", "JavaScript", "JSON"], "socialProfiles": [ { "name": "Twitter", "link": "https://twitter.com" }, { "name": "Facebook", "link": "https://www.facebook.com" } ] } Transforming JSON Data in JavaScriptThe JSON format is syntactically similar to the way we create JavaScript objects. Therefore, it is easier to convert JSON data into JavaScript native objects.
JavaScript built-in JSON object provides two important methods for encoding and decoding JSON data: parse() and stringify().
takes a JSON string as input and converts it into JavaScript object:
// declare a JSON string const me = `{ "name": "Atta", "age": 30, "twitter": "@attacomsian" }` // parse JSON string const data = JSON.parse(me) console.log(data.name) // Atta console.log(data.age) // 30 console.log(data.twitter) // @attacomsiandoes the opposite. It takes a JavaScript object as input and transforms it into a string that represents it in JSON:
const data = { name: 'Atta', age: '30', twitter: '@attacomsian' } // convert it to string const me = JSON.stringify(data) console.log(me) // {"name":"Atta","age":"30","twitter":"@attacomsian"} JSON vs XMLA few years back, XML (Extensible Markup Language) was a popular choice for storing and sharing data over the network. But that is not the case anymore.
JSON has emerged as a popular alternative to XML for the following reasons:
Less verbose — XML uses many more words than required, which makes it time-consuming to read and write.
Lightweight & faster — XML must be parsed by an XML parser, but JSON can be parsed using JavaScript built-in functions. Parsing large XML files is slow and requires a lot of memory.
More data types — You cannot store arrays in XML which are extensively used in JSON format.
Let us see an example of an XML document and then the corresponding document written in JSON:
databases.xml
<databases> <database> <name>MySQL</name> <type>RDBMS</type> </database> <database> <name>MongoDB</name> <type>NoSQL</type> </database> <database> <name>Neo4j</name> <type>Graph DB</type> </database> </databases>databases.json
{ "databases": [ { "name": "MySQL", "type": "RDBMS" }, { "name": "MongoDB", "type": "NoSQL" }, { "name": "Neo4j", "type": "Graph DB" } ] }As you can see above, the XML structure is not intuitive, making it hard to represent in code. On the other hand, the JSON structure is much more compact and intuitive, making it easy to read and map directly to domain objects in any programming language.
JSON ResourcesThere are many useful resources available online for free to learn and work with JSON:
Further ReadingA few more articles related to JSON that you might be interested in:
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.
#JSON
You might also like...How to convert XML to JSON in Node.js
How to send JSON request using XMLHttpRequest (XHR)
How to read JSON from a file using Gson in Java
How to write JSON to a file using Gson in Java
Read and write JSON as a stream using Gson
How to pretty print JSON using Gson in Java
Share it ⟶
The simplest cloud platform for developers & teams. Start with a $200 free credit.
Learn more ⟶
Buy me a coffee ☕
If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️
Enter the number of coffees below: