Working with JSON

JSON (JavaScript Object Notation) is a lightweight, text-based formatting for data exchange. Programmers use it to transmit data from a server to a client and the other way around. Although JSON represents a JavaScript notation, it does not need JavaScript to read or write it. Instead, JSON is an independent language and uses writing conventions and structure like other C-family programming languages like Java, Python, C++, and C#. Web developers use JSON as integration to builds in other languages, like Python.

Why JSON is Important

JSON was specified and popularized in the early 2000s by Douglas Crockford. This programming language came as a need to have a more efficient and fast system of transmitting data between servers.
In those days, servers in HTML pages received and processed requests made by users. The idea of having the server as the primary workforce proved time-consuming and inefficient. A better way to distribute workload was to allow web requests to load in the background rather than refreshing the content from the entire page.

Websites today do more than just display information. They depend on APIs to load content and processes. They are also dependent on social media for verification, signups/sign-ins (for example, Google and Facebook Account API), and other login-dependent areas. As web users make these requests, pages must load quickly and asynchronously.
The job of a front-end developer is remarkably easier with JSON working behind the scenes. JSON is extremely efficient when handling HTTP requests. It loads data and improves response time, offloading a considerable chunk of work away from the frontend developer and away from the client’s main access point to products: webpages.

JSON Vs XML

SOAP and REST APIs

Experts often compare JSON to its predecessor XML (Extensible Markup Language). XML is also a data exchange format for storing information on the server-side and web delivery. It is used exclusively for SOAP (Simple Object Access Protocol) messaging protocol. SOAP is XML's way of defining what information goes out and how. It extends HTTP for XML messaging and provides data transport for web services.
JSON took over from XML and became a more preferred way of transmitting and storing temporary data, eventually giving rise to another messaging protocol: REST (Representational State Transfer).

As JSON thrived, REST also became the preferred messaging protocol and soon it overtook SOAP. REST also had a big advantage: it allowed data formats like XML, HTML, and JSON, unlike SOAP which only tolerated XML.
XML and JSON share similarities: programmers use them both to transmit data from client to server and vice versa. They are also both platform and language independent. But there are key differences that have made JSON a more superior choice.

  1. JSON is a more readable format. It does not use end and start tags like XML
  2. It supports arrays. XML does not
  3. It represents objects while XML supports data items
  4. It is less verbose and faster than XML

The Structure and Syntax of JSON

The JSON structure is likened to JavaScript objects and Python dictionaries, although its major functions differ. JSON has two main structures:

Array: An ordered list of values. This opens and closes with square brackets - [ ].

"cars": [ 
  "ford", 
  "volvo", 
  "ferrari" 
]

Object: This is the widely used form of JSON. It is an unordered collection of key and value pairs separated by a colon. It opens and closes with curly braces { }.

"book": { 
  "name": "Things Fall Apart", 
  "author": "Chinua Achebe", 
  "year": 2000, 
  "genre": "Fantasy Fiction", 
  "bestseller": true 
}

Nested structures could contain objects inside of arrays or arrays inside of objects.

const StudentData = { 
  "name": "Regina White", 
  "age": 22, 
  "hobby": { 
    "reading" : true, 
    "gaming" : false, 
    "sport" : "volleyball" 
  }, 
  "social_handles" : [ 
    { 
      "site" : "twitter", 
      "link" : "https://twitter.com/" 
    }, 
    { 
      "site" : "facebook", 
      "link" : "https://www.facebook.com/" 
    }, 
    { 
      "site" : "tiktok", 
      "link" : "https://tiktok.com/" 
    } 
  ],
  "classes" : ["Mathematics", "English", "Physics", "Chemistry"] 
}

Accessing JSON Data

There are two ways of accessing data in a JSON program - dot notation or brackets. For arrays, we could also use the typical indexing system to get inner values.

Say we have the following set of data:

const StudentData = { 
  "name": "Regina White", 
  "age": 22, 
  "hobby": { 
    "reading" : true, 
    "gaming" : false, 
    "sport" : "volleyball" 
  }, 
  "social_handles" : [ 
  {
    "site" : "twitter", 
    "link" : "https://twitter.com/" 
  }, 
  { 
    "site" : "facebook", 
    "link" : "https://www.facebook.com/" 
  }, 
  { 
    "site" : "tiktok", 
    "link" : "https://tiktok.com/" 
  }],
  "classes" : ["Mathematics", "English", "Physics", "Chemistry"] 
}

Using the dot notation

// accessing JSON Student data 
console.log(StudentData.name); // Regina White 
console.log(StudentData.hobby); // { reading: true, gaming: false, sport: "volleyball"} 
 
console.log(StudentData.hobby.sport); // volleyball 
console.log(StudentData.social_handles[1].site); // facebook

Using brackets

// accessing JSON object using brackets 
console.log(Student data["name"]); // Regina White
console.log(Student data["hobby"]["sport"]); //Volleyball

JSON Data Types

JSON has six data types - string, number, boolean, object, null, and array.

JavaScript Object Literals VS JSON

From the above code structure, we can see how closely JSON syntax resembles JavaScript Object literals and how we can easily confuse it with other structures. But here are three key differences that set JSON apart from other JavaScript-based constructions:

  1. JSON requires that both the key and values be enclosed in quotes. In contrast, in the JavaScript Object literals, the key is not enclosed in brackets
  2. JSON does work with functions. JavaScript Objects does.
  3. JSON can be stored externally in a file with a .json extension and linked to an HTML page. JavaScript Objects are always written right in the JavaScript code.

Parse() and Stringify()

Parse() and stringify() are built-in functions for converting JSON data to objects and vice versa.

Parse() - converts JSON data to a JavaScript object.

// json object 
const jdata = '{ "name": "Regina White", "age": 22 }'; 
 
// converting to JavaScript object 
const obj = JSON.parse(jData); 
 
// accessing the data 
console.log(obj.name); // Regina White 

Stringify() - converts JavaScript Object to JSON

// JavaScript object 
const Data = { "name": "Kingsley Peters", "age": 20 }; 
 
// converting to JSON 
const obj = JSON.stringify(Data); 
 
// accessing the data 
console.log(obj); // "{"name":"Kingsley Peters","age":20}" 

Loading a JSON file to HTML

<html> 
<head> 
  <title>JSON DEMO</title> 
</head>
<body>

<script language = "javascript"> 
//Here the JSON data format is written directly in the HTML page and accessed with DOM manipulation 
var student1 = {  
  "rollnum": "001", 
  "name": "Regina White", 
  "age": 22, 
  "classes" : ["Mathematics", "English", "Physics", "Chemistry"],
  "degree": "BTech", 
  "Faculty": "Faculty of Science"
};

document.write ("<p>Roll Number = " + student1.rollnum+"</p>"); 
document.write ("<p>Name of Student = " + student1.name+"</p>");   
document.write ("<p>Classes Taken = " + student1.classes+"</p>");    

document.write ("<p>Faculty = " + student1.faculty+"</p>");  
document.write ("<p>Degree to be earned = " + student1.degree+"</p>");  

var student2 = {
  "rollnum": "002", 
  "name": "Kingsley Peters", 
  "age": 20, 
  "classes" : ["History", "English", "Government", "Chemistry"],
  "degree": "BA", 
  "Faculty": "Faculty of Arts" 
}; 

document.write ("<p>Roll Number = " + student1.rollnum+"</p>"); 
document.write ("<p>Name of Student = " + student1.name+"</p>");   
document.write ("<p>Classes Taken = " + student1.classes+"</p>");    

document.write ("<p>Faculty = " + student1.faculty+"</p>");  
document.write ("<p>Degree to be earned = " + student1.degree+"</p>");  

var student3 = {  
  "rollnum": "003", 
  "name": "Linda Forson", 
  "age": 22, 
  "classes" : ["Chemistry", "English", "Biology", "Commerce"],
  "degree": "BSc", 
  "Faculty": "Faculty of Science" 
}; 

document.write ("<p>Roll Number = " + student1.rollnum+"</p>"); 
document.write ("<p>Name of Student = " + student1.name+"</p>");   
document.write ("<p>Classes Taken = " + student1.classes+"</p>");    
          
document.write ("<p>Faculty = " + student1.faculty+"</p>");  
document.write ("<p>Degree to be earned = " + student1.degree+"</p>");  

var student4 = {  
  "rollnum": "004", 
  "name": "Daniel James", 
  "age": 25, 
  "classes" : ["History", "Computer", "Biology", "Commerce"],
  "degree": "BSc", 
  "Faculty": "Faculty of Science" 
}; 

document.write ("<p>Roll Number = " + student1.rollnum+"</p>"); 
document.write ("<p>Name of Student = " + student1.name+"</p>");   
document.write ("<p>Classes Taken = " + student1.classes+"</p>");    
          
document.write ("<p>Faculty = " + student1.faculty+"</p>");  
document.write ("<p>Degree to be earned = " + student1.degree+"</p>");  
</script> 

</body> 
</html>

Document Database or NoSQL Database

A document database, also called NoSQL database, represent an alternative data model to popular relational databases like SQL. The main characteristics of NoSQLs are that they come in document form and key-value pairs. They query and store data in JSON formats rather than the typical tabular form of rows and columns. The NoSQL database model is fast becoming a worthy alternative to tabular databases and JSON is right at the heart of it.
In a short time, developers have embraced the NoSQL model because of its flexibility, intuitiveness, and scalability. One of its biggest flexes is that developers do not have to plan schemas ahead of coding. The database is flexible enough that they evolve with the application. This condition reduces time spent on creating data models and promotes faster software development cycles.
JSON's document database also provides rich data structures, allowing data to be structured in a way developer prefers – through graphs, key-value pairs, time series, rich objects, or geospatial data.

Advantages of JSON

  • JSON is known for being lightweight. A feature that makes it executes responses fast
  • It enjoys extensive browser support
  • It is easy to read and understand
  • It stores data in no-relational databases

As wonderful as JSON is, it does have its downsides. Some of its disadvantages include:

  • It is not very secure compared to XML
  • It is limited to only six data types
  • It is not self-describing like XML

Conclusion

JSON's easy-to-read format and ease of use have made it a de facto format in data transmission today. It has been adopted extensively by big tech companies like Google, Twitter, and Facebook. Twitter used XML up until 2013 when they dropped it in favor of using JSON exclusively.

XML emerged in the 90s as a strong factor in organizing content and helped JSON take it a step further in its attempt to broadcast universal messages without special parsing. The big future for JSON is not only marked by the success of its big brother JavaScript. Its enormous potential is also rooted in its ability to communicate across programming languages – a true sign of innovation through inclusion.

Author

Kris Terziev

Kris is the Head of Research and Development at CodeCoda and, as he himself says, is constantly seeking better methods of developing and implementing software solutions.
In his previous experience as a software engineer, he has experienced everything from plain assembly code through the optimization of the process of business and functional analysis and the development of Fintech Applications.
During his school years, he won several medals in international competitions in mathematics and computer science. Concerning his professional interests, he pays special attention to algorithms and software development methodologies.