Many people think of JSON (JavaScript Object Notation) as a language, but it's really just a lightweight data interchange format that works natively with different programming languages, like Python, Java, PHP, and JavaScript. JSON is commonly used for transmitting data in web applications.
As the name implies, JSON is very similar to JavaScript objects in the way it's written and stored. However, JSON has only properties and no methods.
In this article, we will deep dive into what JSON is, JSON syntax, JSON data examples, and why we need JSON.
Table of contents
JSON is a text-based data exchange format and is syntactically similar to JavaScript objects.
You can use JSON when writing asynchronous web applications that exchange data from server to a web page and need very fast data access—for example, websites having dynamic content that needs to update based on user input, or suggestions based on user preferences.
JSON is a text-based data interchange format for passing data between client and server over a network.
Here is an example of data stored in JSON format:
{
"studentDetails": {
"name" : "Joe",
"age" : 16,
"dept" : "computers",
"hobbies" : ["dance", "books", "public speaking", "golf"],
"isClassLeader" : false,
"address": {
"villa number": 23,
"street": "Bakerville 2nd",
"county": "Essex County",
"zip": "07042"
"state": "NJ"
}
}
}
Let’s explain the JSON syntax:
When a formal schema is needed, it's possible to create one following the JSON schema standards.
Unlike JavaScript objects, JavaScript Object Notation cannot accept functions, date type, and undefined type. Dates can be converted to string in ISO format and stored.
You can create JSON objects inside an array, and arrays inside those JSON objects, as well:
{
"continentName": "North America",
"area": 24.71,
"countries": [
{
"countryName" : "Mexico",
"countryCode" : "+52",
"location" : "south of north america",
"languagesSpoken" : ["spanish", "maya", "nahuatl"]
}
]
}
This can get more complex as more information is added. But you can easily validate the JSON syntax using online JSON validators.
JavaScript natively supports switching between JavaScript objects and JSON string using the in-built global object: JSON.
Use the JSON.stringify() method to convert JS objects to JSON strings that can be easily sent to the server. This is called serialization.
Use the JSON.stringify() method to convert JS objects to JSON strings that can be easily sent to the server. This is called serialization.
const new_user = {
name: "Mary Mark",
age: 25,
email: "mary.mark@gmail.com",
tech_skills: ["Java", "JavaScript", "Python"]
};
const jsonString = JSON.stringify(new_user);
console.log(jsonString);
Output:
{"name":"Mary Mark","age":25,"email":"mary.mark@gmail.com","tech_skills":["Java", "JavaScript","Python"]}
On the client side, you need to deserialize the string back so that it can be presented to the user. For deserialization—i.e., converting JSON string to JS object—you can use the JSON.parse() method:
const jsonString = '{"name":"Mary Mark","age":25,"email":"mary.mark@gmail.com","tech_skills":["Java", "JavaScript","Python"]}';
const userDetails = JSON.parse(jsonString);
You can then get the individual items as userDetails.name, userDetails.age, and so on. If you want to get all the details, you can use a loop and iterate through it:
for (let key in userDetails) {
const value = userDetails[key];
console.log(key, value);
}
Similarly, other languages like Python, Java, and C# also provide code for parsing and generating JSON data.
There are many tools to validate JSON. You can use online tools, IDE plugins, text editors, or programming language libraries to ensure that your JSON data follows the right standards and is correctly formatted. It is useful to utilize the validator when there is a huge amount of data. The validations can be:
The basic syntax of opening and closing curly braces, and usage of square brackets for arrays.
Using double quotation marks for keys and string values, and commas to separate each key-value pair.
Data type validation and correct formatting for data types—for example, numbers should not be enclosed in double quotes, boolean values cannot be anything other than true/false, and so on.
Structural validation of arrays, objects, and nested structures.
Optionally, supportive of JSON schema validation, ensuring that the JSON documents follow the specified type and constraints as per the schema.
Displaying errors wherever applicable so that the user can easily correct them.
JSON was popularized by Douglas Crockford, who aimed to find an easier way than XML to transmit data between the browser and web server. Already working with JavaScript, Crockford tried to send the first message from client to server using JavaScript object literals. The message had key-value pairs, but the keys were not in double quotes, causing JavaScript to reject it because he used a reserved keyword as a key. Crockford sought a simple solution: adding double quotes to the keys, which worked!
The next step was to convince the world that JSON was a superior format—light-weight, flexible, and easy to read. For this, in 2002, Crockford registered the domain name json.org.
Later, between 2004 and 2005, with the advent of AJAX (Asynchronous JavaScript and XML) and single page applications (SPAs), JSON's popularity began to rise, and since then, there has been no looking back. Many popular programming languages soon provided native methods to handle JSON data, making it easier to convert and use data between the front end and back end.
As data exploded, companies needed to store a mix of unstructured and structured data. JSON, being flexible, became the best way to transmit such data. This led to the emergence of document databases that stored data in JSON formats, making JSON a popular choice for end-to-end web development.
As we highlighted earlier, the most common use case of JSON is to transmit data in web applications. Some typical use cases of JSON are:
Transporting data between client and server in a web page: Before JSON, data was transported using formats like XML. However, these have a lot of extra overheads, especially parsing and data mapping. JavaScript Object Notation is light-weight and flexible, and all that is transferred from client to server and back is data! Also, the data is easy to read in name-value pairs.
Reducing development time of web applications: JavaScript is one of the essential languages used for web development. JS stores all the data collected from a user—for example, form data—as objects. This data can be sent to the server (back-end) without much coding effort using JSON.
Faster availability of data: Most web pages nowadays are asynchronous, where data should be available faster and without a page refresh. Using JavaScript, applications can quickly send data in JSON syntax.
Configuration files: JSON is often used for storing application settings, like preferences or environment variables and application and system metadata.
Logging and error reporting: JSON format is easy to parse and search for, hence logging data is stored in JSON format so it can be easily analyzed.
Data storage in NoSQL databases: Databases like MongoDB use JSON-like format to store data.
Let us create an end to end workflow to illustrate how using JSON syntax simplifies the entire process of calling an API endpoint and getting the response. Let us take the simple example of a new user registration. Here are the steps involved:
Client sends the request by calling the API endpoint, using HTTP methods (post, get, delete, and put), and puts the user data into JSON objects and sends them to the backend server.
The back end can be anything, like Node.js, Spring, Django, etc. The back end validates and processes the data—like verifying mandatory fields, hashing the password field, and so on—and creates a new document to be saved in MongoDB (that stores the data in BSON, a JSON-like format).
Once the database operation is done, the server constructs a JSON response and sends it to the client.
The client receives and parses the response for further actions.
JSON data is easily readable and works with most programming languages using libraries without the need for writing extensive code to handle it, which makes the process fast and efficient.
Using native drivers, web applications can directly send data to MongoDB in JSON format. MongoDB internally stores data as BSON (Binary JSON), which is faster compared to JSON itself when it comes to querying the data. Also, BSON storage is more flexible and space-efficient. Using BSON at the back end also saves a lot of code for developers as there is no need for object mapping or conversions.
An important feature of JSON is that it’s very easy to fetch values, even from nested objects.
Consider the object defined in the previous example: to fetch values. We need to assign the object to a variable.
let exampleJsonObj = {
"continentName": "North America",
"area": 24.71,
"countries": [
{
"countryName" : "Mexico",
"countryCode" : "+52",
"location" : "south of north america",
"languagesSpoken" : ["spanish", "maya", "nahuatl"]
}
]
}
Note: To try the below JSON examples, you can simply create a .html, and add the code inside <script>
tags.
For example, you can get the “continentName” from our previous example, simply by giving the object name and the key:
document.write(exampleJsonObj.continentName);
This will print the answer North America on the page. To get the value of an array, you should specify the index. Just like in most other programming languages, the index starts with 0. So, to get the value of location, you should type:
document.write(exampleJsonObj.countries[0].location);
To get all the languagesSpoken, type:
document.write(exampleJsonObj.countries[0].languagesSpoken);
To get a specific language, you can add the index to the languagesSpoken key:
document.write(exampleJsonObj.countries[0].languagesSpoken[1]);
To print the value of entire object, convert the object into string, using the stringify() method, and then print the string:
let jsonString = JSON.stringify(exampleJsonObj);
document.write(jsonString);
eXtensible Markup Language is yet another data interchange format. However, it has a lot of payload attached, making it verbose. If you look at XML schema, there are opening and closing tags for every item, which make it look like a complex structure. Further, parsing XML is tedious work and requires writing a good amount of code, when compared to JSON, which can be parsed in a simple manner using the JavaScript utility function.
JSON schema is mostly self describing, whereas XML is validated using XSD, which is again complex. However, if detailed definitions are required, like for SOAP services or legacy systems, XML is more suitable.
An example of how JSON data vs XML data looks is shown below:
Json
{
"name": "Mary Mark",
"age": 25,
"email": "mary.mark@gmail.com",
"tech_skills": [
"Java",
"JavaScript",
"Python"
]
}
XML
<user>
<name>Mary Mark</name>
<age>25</age>
<email>mary.mark@gmail.com</email>
<tech_skills>
<tech_skill>Java</tech_skill>
<tech_skill>JavaScript</tech_skill>
<tech_skill>Python</tech_skill>
</tech_skills>
</user>
A JSON document database is a NoSQL database that stores, retrieves, and manages data in JSON format. A JSON database can handle large volumes of unstructured or structured data and offer flexible schema, i.e., there are no schema changes required to the database, if a field needs to be added, modified, or removed. You can also store nested objects and arrays within the document itself, thus having a hierarchical structure, as well as all the related data in one place.
MongoDB is one of the most popular databases that stores documents in BSON (JSON-like) format. The reason to use BSON is to support a few additional data types, like ObjectId, Date, and regular expressions. MongoDB provides rich query capabilities using its aggregation framework and is known for horizontal scalability and high performance.
Here is a snapshot of how data is stored in MongoDB Atlas:
JSON is easy to learn, especially if you are familiar with JavaScript. It's easier to parse JSON as opposed to XML. JSON supports flexible schema. Most of the modern programming languages—like Java, Python, and Ruby—extensively support JSON. JSON is compatible with all the major browsers. It's an ideal data exchange format for web applications that use JavaScript as the front end and MongoDB as their data platform, as MongoDB stores data in BSON, which offers a few more benefits on top of JSON.
JSON, or JavaScript Object Notation, is a text-based data interchange format that is used for transmitting information between web application clients and servers. JSON is light-weight and enables faster data transport.
JSON is a text-based, light-weight data interchange format used to transmit data from server to client in web applications. It’s a convenient method of data transport because of its similarity to JavaScript objects. A simple example of JSON is:
{ “countryName” : “Mexico”, “countryCode” : “+52” }
JavaScript is a programming language, whereas JSON is just a data exchange format.
JSON does not support functions, whereas JavaScript has many pre-defined as well as user-defined functions. JavaScript has in-built methods to convert objects into JSON strings and vice versa, to enable faster data transfer between web application client and server.