Understanding JavaScript Object Notation (JSON)
The JSON format is a popular way to share data online. It stands for JavaScript Object Notation. JSON syntax is based on JavaScript, but you don’t need to know JavaScript to use it. One of the reasons JSON is so popular is that it can be used with virtually any programming language.
In addition to API requests and responses, JSON is widely used in application configuration files. XML (Extensible Markup Language) was popular before JSON was created.
// JSON
{
"name": "Neeraj Kushwaha",
"degree": "MS",
"country": "India"
}
// XML
<?xml version="1.0" encoding="UTF-8" ?>
<root>
<name>Neeraj Kushwaha</name>
<degree>MS</degree>
<country>India</country>
</root>
As a human-readable format, JSON has several advantages. There are more extraneous characters in XML, and the data label is repeated in the opening and closing tags. Not only does this create visual clutter that interferes with human readability, but it also increases the number of characters required to encode the same data. As a result, XML data generally requires more bytes. Online, fewer bytes mean that a large file can be downloaded more quickly, and browsers can display website content more quickly. There are two reasons why JSON has become the most popular data encoding format on the web today: human readability and file size.
What’s an Object in JSON?
The acronym JSON stands for JavaScript Object Notation. It’s pretty straightforward to understand the JavaScript part of that name. It is JavaScript that provides the syntax for JSON. N stands for Notation, which is pretty self-explanatory. In other words, notation refers to a way of presenting information that has its own format and rules. In JavaScript Object Notation, objects refer to a technical meaning. Like other programming languages, JavsScript objects are collections of data. There are key-value pairs in an object, where the key is a label describing the data, and the value is the data. Another JavaScript data structure that can be represented as JSON is an array. Arrays are lists of values arranged in order. Arrays don’t have keys.
// JavaScript Object { website: 'https://www.learncsdesign.com', author: 'Neeraj Kushwaha', } // JSON { "website": "www.learncsdesign.com", "author": "Neeraj Kushwaha" }
// JavaScript Object [ 'Java', 'C', 'Go', ] // JSON [ "Java", "C", "Go" ]
Rules for JSON Structure
- Both JavaScript objects and JSON that store key-value pairs start and end with curly braces. The beginning and ending characters of JavaScript arrays and JSON are square brackets.
- JavaScript doesn’t require punctuation around keys, but single quotes or double quotes are acceptable. JSON requires double quotes around the key. In JavaScript, I don’t need quotes on the left, but in JSON, I do. A colon follows the key in both cases.
- Strings, numbers, true false values, arrays, and other objects can be stored in JavaScript objects as values. A string value in JavaScript must be enclosed in quotes, but in ES6, these can be single or double quotes or even backticks. Strings in JSON must be enclosed in double quotes, there is no room for personal style.
- A comma separates one key-value pair from another in both JavaScript and JSON. It’s not necessary to quote numerical values in JavaScript or JSON, but JSON has an additional rule for numbers, they can’t start with 0. JSON can simply be represented as a number with no leading zero if this truly is a numerical value. Nevertheless, if the zero is significant, I might need to represent this as a string instead, enclosing it in quotes, and relying on the system to handle it accordingly.
- A numerical value in JavaScript can end with a decimal point, but not in JSON. Usually, this just means that you need to ensure the decimal is removed.
- JavaScript or JSON do not require quotes for boolean values, which have a value of true or false.
- Every key-value pair in a JavaScript object should have a comma at the end, even if it’s the last one. JSON, however, does not support trailing commas. The final key-value pair cannot have a comma after it.
- In JavaScript objects, comments are also supported, but not in JSON. JSON doesn’t support comments syntax, so you can’t insert a comment to explain or document your code. JavaScript supports comments, but parsers ignore them when the code runs.
- Microsoft created JSON-C, also known as JSON with Comments, which is used by Visual Studio Code.
// JavaScript Object { model: '2022', brand: "Hyundai", color: `red`, version: 2., delcode: 09, // PDI check done pdi: true, } // JSON { "model": "2022", "brand": "Hyundai", "color": "red", "version": 2, "delcode": 9, "pdi": true }
Basic JSON Syntax Rules
- Strings and keys should be enclosed in double quotes
- Numbers must not have leading zeros
- Numbers should not contain trailing decimals
- There should be no trailing comma
- Comments are not allowed
JSON Processing
Although JSON data is generally shared as a string of characters, it is useful as a notation because it describes structures, such as objects and arrays. When creating a JSON string from an object or array, how does a programming language work with a JSON string?
In order to use JSON, programming languages must convert it into a structure, and they must convert structures from the language into JSON. Serialize and deserialize are terms that are commonly used when dealing with JSON. JSON serialization is the process of converting a structure into a JSON string, whereas JSON deserialization is the process of converting a JSON string into a structured object that can be used by a programming language.
Even though JSON is based on JavaScript’s object notation, it can be used across many languages and platforms.
Example in JavaScript When receiving data from a web server, the data is always a string. Parse the data with JSON.parse(), and the data becomes a JavaScript object. const obj = JSON.parse('{"name":"Neeraj", "age":41, "city":"New Delhi"}'); When sending data to a web server, the data has to be a string. Convert a JavaScript object into a string with JSON.stringify(). const myJSON = JSON.stringify(obj);
JSON Schema
When you request JSON data, what happens when the data you receive is different from what you expected?
The JSON might be arranged differently than your code expects, or it might not be a valid response.
This type of situation can be identified and dealt with using a schema. It is essentially a blueprint for what data should look like. The code that handles the data can be provided with a schema for the data you expect to receive. By comparing the schema to the data, your code can verify that the data is what you expect or that there is a problem.
The JSON Schema standard is used for creating schemas for JSON data. The Internet engineering task force created it.
Using JSON Schema, you create JSON based on a specific structure, keywords, and values. Code can then be written to validate data against the schema.
It’s also important to know what a schema cannot do for you. You can use a schema to describe the general structure of data, but you can’t really understand the meaning of the data itself to decide whether it makes sense. Suppose you have JSON data for something like a shopping cart. A total order includes a number of items and their prices, along with tax and shipping. If you want to verify that the price, tax, shipping, and total values are all numbers, you can use a schema. It is not possible to verify that the total value is equal to the sum of item prices, tax, and shipping, or that the total value is greater than any of its components. You must write code that works with and compares values for this kind of validation.
Example
This example provides a typical minimum you are likely to see in JSON Schema. It contains:
- $id keyword
- $schema keyword
- title annotation keyword
- type instance data model
- properties validation keyword
- Three keys: firstName, lastName, and age each with their own:
* description annotation keyword.
* type instance data model. - minimum validation keyword on the age key.
JSON sample data to validate:
{
"firstName": "Neeraj",
"lastName": "Kushwaha",
"age": 41
}
If you want to play around with it, you can use any validator for JSON schemas, such as jsonschemavalidator.net or npm.runkit.com/ajv
JSON Schema Generator
Creating a JSON schema from scratch can be challenging and time-consuming. If you use a schema generator like the one at jsonschema.net, you’ll be able to code the components and basic structure more quickly.
Schema generators allow you to enter examples of valid JSON and select schema options. Your data is then automatically transformed into a schema based on your selections.
Semantic markup using JSON-LD
Creating JSON structures and schemas for data is simple, but integrating data from another organization or receiving data from someone else often requires human intervention.
By adding semantic markup to your data, you can automate tasks like this. By using a common vocabulary of objects and key names, semantic markup not only organizes data but also indicates its meaning. JSON-LD, which stands for JSON for linking data, is a popular semantic system based on JSON.
The JSON-LD format is a lightweight Linked Data format. Humans can easily read and write it. Based on the successful JSON format, it allows JSON data to be interoperable at the Web scale. In programming environments, REST Web services, and unstructured databases such as Apache CouchDB and MongoDB, JSON-LD is an ideal data format.
To convey the meaning of content, JSON-LD adds a couple of standards. It references common vocabularies maintained by a variety of organizations, including schema.org and the W3C. Using the JSON-LD standard, key names are also derived from vocabularies that are references. These two JSON-LD features enable an application to parse data and determine what it contains and how to use it.
For search results, Google encourages websites to include JSON-LD in their HTML. Additionally, JSON-LD allows applications to examine data from multiple sources and identify how they relate.
JSON-LD generator
JSON-LD is relatively straightforward to write for small snippets, but automatic JSON-LD generators can be very helpful for larger content or content that relies on more than one vocabulary type. A tool such as webcode.tools can help you generate JSON-LD using options in the form.
Summary
It’s now clear to you what JSON is and how it’s used to structure and exchange data.