top

Search

Software Key Tutorial

.

UpGrad

Software Key Tutorial

JSON Tutorial

Introduction

JSON is a text-based format for representing structured data that is based on the syntax of JavaScript object literals. However, JSON is language-agnostic and can be used with many programming languages, including JavaScript, Python, Ruby, PHP, and Java. In this JSON Tutorial, we will delve into various aspects of JSON.

Douglas Crockford originally created JSON in the early 2000s as a subset of JavaScript syntax to transmit data between a server and a web application. The intent was to have a lightweight transport format that was easier to parse than XML.

This JSON tutorial will discuss in detail the features of JSON.  It is now supported in all major programming languages and platforms either natively or through libraries. JSON has almost entirely replaced XML in web services and APIs. Major websites and applications that use JSON include Twitter, GitHub, Facebook, and Google.

Overview

JSON has become the standard format for transmitting JSON data between applications and web services. It is commonly used for transmitting data between a server and a web application or mobile app. It is the main format for data exchange used in REST API web services. JSON is also used extensively in client-side JavaScript for handling data and configuration files.

In this JSON tutorial, we will check the advantages and disadvantages of JSON as a data exchange format.

What is JASON?

JSON stands for JavaScript Object Notation. It is a lightweight, text-based, language-independent data exchange format that is easy for humans and machines to read and write. 

Some key characteristics of JSON are:

  • JSON is built on two structures:

  1.  A collection of name/value pairs: This is represented in JSON as { "key1": "value1", "key2":  

   "value2", ... }

Example:

{
"name": "John",
"age": 30
}
  1. An ordered list of values: This is represented in JSON as [ "value1", "value2", ... ]

Example:

[
"red",
"green",
"blue"
]
  • JSON data is written in key/value pairs, similar to JavaScript object literals:

{
  "name": "John",
  "age": 30,
  "city": "New York" 
}
  • Keys and values are separated by a colon (:). A comma separates each key/value pair (,).

  • Curly braces hold objects ({ }) and square brackets hold arrays ([ ])

  • JSON keys must be strings enclosed in double quotes (""). JSON values can be strings, numbers, boolean values, arrays, objects, or null.

  • JSON uses JavaScript syntax for primitive data types:

- Numbers are unquoted

- Boolean values are unquoted (true or false)

- Null is unquoted (null)

- JSON files have the file extension .json

JSON formats are easy for machines to parse and generate. This makes JSON an ideal data interchange format. For those who want to see the data in a more structured manner, a JSON formatter can be used.

JSON Example

When you look at a JSON example, you'll notice its clarity.

Here is an example of a JSON object that represents a person:

{
  "firstName": "John",
  "lastName": "Doe",
  "age": 30,
  "address": {
    "streetAddress": "123 Main St",
    "city": "Anytown",
    "state": "CA",
    "postalCode": "12345"
  },
  "phoneNumbers": [
    "123-456-7890", 
    "987-654-3210"
  ],
  "children": [],
  "spouse": null
}

This example shows several types of values that can be represented in JSON:

  • String - The "firstName", "lastName", and "streetAddress" values are strings enclosed in double quotes

  • Number - The "age" value is a number

  • Object - The "address" value contains nested objects with street address, city, state and postal code attributes

  • Array - The "phoneNumbers" value contains an array of phone number strings

  • Boolean - The "children" value is an empty array, implying no children

  • null - The "spouse" value is null meaning no spouse exists

The key names in JSON objects provide semantic meaning and structure to the data. This makes it easy to reason the data. JSON can also represent ordered lists of values using arrays:

[
  "Toyota", 
  "Ford",
  "Chevy",
  "Tesla" 
]

Use of JSON objects or arrays depends on the data being represented. But both provide a simple, lightweight way to represent structured data that can easily be parsed and understood.

Features of JSON

JSON has several important features that have helped make it the most popular data-interchange format:

1. Lightweight

JSON is a lightweight text-based format that is much less verbose than XML. The simple syntax makes JSON documents very compact compared to XML.

For example, here is the data represented in JSON:

{"employees": [{"firstName":"John", "lastName":"Doe"}]}

And the equivalent in XML: 

The JSON version takes up much less space, with less syntax overhead.

<employees>
  <employee>
    <firstName>John</firstName> 
    <lastName>Doe</lastName>
  </employee>
</employees>

2. Human Readable

JSON is designed to be easy for humans to read and write. With proper indentation and line breaks, it is almost as readable as YAML or Python. The property-value pairs map intuitively to how data structures work in most programming languages.

JSON Vs. XML: Compare the readability for the same data

JSON

{
  "name": "John Smith",
  "age": 27,
  "address": {
    "streetAddress": "21 2nd Street",
    "city": "New York"
  }
}

XML

<person>
  <name>John Smith</name>
  <age>27</age>
  <address>
    <streetAddress>21 2nd Street</streetAddress>
    <city>New York</city>
  </address>
</person>

The nested syntax of JSON objects and arrays makes it easy to represent relational data intuitively.

3. Language Independent

JSON is considered a universal data format. It was inspired by JavaScript but can be used with any programming language. There are JSON libraries available for almost every language. This makes it easy to read, write, parse, and generate JSON from any language.

4. Self-Describing

JSON is self-describing. It is structured with key/value pairs, making it a clear JSON structure. The data includes metadata that describes the type of data and the relationship between values. For example, values are labeled with keys like "firstName" and "lastName" in a JSON object, making them semantically meaningful without extra documentation.

5. Extensible

New keys and values can easily be added to JSON objects without breaking existing parsers. This enables extending JSON schemas to support new data as needed.

6. Parsers Widely Available

There are JSON parsers available for virtually every programming language and platform. This allows seamless conversion back and forth from JSON to native data structures.

7. Used by Many Web Services

JSON is the primary data format used by most REST API web services today. Platforms like ASP.NET make it easy to parse JSON requests and return JSON responses. The widespread support has made JSON the lingua franca for web service data exchange.

JSON Syntax Rules

JSON has strict syntax rules that must be followed.

  • Data is represented in name/value pairs - This is done using JavaScript object literal syntax - { "name": "value"}

  • Names must be strings enclosed in double quotes - Only string values need to be enclosed in quotes in JSON.

  • Values can be strings, numbers, arrays, booleans, or other JSON objects - Values do not have to be enclosed in quotes except for strings.

  • Strings are enclosed in double quotes - All JSON string values must be enclosed in double quotes like "John"

  • No trailing commas - There cannot be a comma after the last item in a collection or object.

  • Arrays values must be enclosed in square brackets [ ]

  • Object values must be enclosed in curly braces { }

  • Nested objects and arrays are allowed - Values can recursively contain arrays or nested objects.

Valid JSON snippet examples:

// Strings in double quotes
{ "name": "John" }


// Number
{ "age": 35 } 


// Array in []
{ "colors": ["red", "green", "blue"] }


// Object in {} 
{
  "address": {
    "street": "123 Main St",
    "city": "Anytown" 
  }
}


// Nested array
{
  "data": [
    [0, 1, 2],
    [3, 4, 5]
  ]
}

Invalid JSON examples:

// No quotes around names
{ name: "John" } 


// Trailing comma
{ "name": "John", }


// No quotes around string
{ "name": John }


// Single quotes around string 
{ 'name': "John" }


// Unquoted values
{ "age": 45, "employed": false }

Following these syntax rules rigorously allows JSON to be parsed consistently across different languages and platforms.

json.dumps()

The json.dumps() method takes a Python object and converts it into a JSON string.

For example:

import json

person = {"name": "John", "age": 30}

person_json = json.dumps(person)

print(person_json)

// Output: {"name": "John", "age": 30}

The json.dumps() method allows additional arguments to control formatting, such as indentation and sorting keys.

json.loads()

The json.loads() method parses a JSON string and converts it into a Python object.

For example:

import json

person_json = '{"name": "John", "age": 30}'

person = json.loads(person_json)

print(person["name"])

// Output: John

The object returned by json.loads() can be accessed like a normal Python object.

These methods allow easy conversion between JSON strings and Python data structures. Using json.dumps() to serialize objects to JSON strings and json.loads() to deserialize JSON strings into objects is a common pattern in Python web services and APIs.

Advantages of JSON

Key advantages of using JSON are:

  • Lightweight and compact - JSON documents take less space compared to XML. Parsing is also faster due to less data.

  • Easy to read and write - JSON has a minimal syntax that is easy for humans to process manually.

  • Language independent - JSON support exists for virtually all modern programming languages.

  • JSON is schema-less - Unlike XML, JSON does not require a schema definition. Formats can evolve organically.

  • Development is fast and flexible - JSON is great for agile development and continuous deployment cycles.

  • Ideal for web services - JSON is better than XML for web service API data exchange. JSON requests/responses are faster.

  • Simpler than XML - JSON is simpler to parse than XML since it does not require reading schema definitions. The straightforward mapping to native data types makes processing easy.

  • Self-documenting - JSON is semantic and self-describing with meaningful keys and values.

  • JSON can use JavaScript syntax - Since it is based on a subset of JavaScript syntax, JSON can seamlessly integrate with JavaScript code.

Disadvantages of JSON

However, JSON also comes with some disadvantages:

  • No built-in schema or validation - Unlike XML, JSON does not have a schema language built-in. Validation requires custom code.

  • No comments - JSON does not support comments like XML. But many parsers allow JavaScript-style // and /* */ comments.

  • Arrays cannot represent sets - JSON arrays are ordered, which does not map well to represent unordered sets.

  • Browser security restrictions - Browsers block requests to external JSON files due to the same origin policies unless CORS is used.

  • No querying capabilities - JSON itself does not support querying or filtering data like XML/SQL. This requires additional code.

  • No namespace support - XML namespaces are not supported in JSON.

While the advantages generally outweigh the disadvantages, JSON may not make sense for every use case. XML still has benefits when extensive validation, querying, or domains are required.

Conclusion

JSON provides an intuitive way to represent structured data that is easy for humans and machines to read and generate. It is built on two main structures - objects and arrays. It uses JavaScript object literal syntax to represent attribute-value pairs and ordered values. However, JSON is language-independent and can be used with any modern programming language seamlessly.

The minimal syntax, lack of verbosity, human readability, and widespread tooling support have made JSON the predominant format for web APIs and data exchange on the internet today. It has almost entirely replaced XML for web service integration.

Any application dealing with data transfer or storage should use JSON for a simple, universal and language-independent solution.

FAQs

  1. How efficient is JSON compared to XML?

Generally, JSON parsing is faster and more lightweight than XML. The simpler syntax results in smaller message sizes compared to equivalent XML.

  1. How is JSON replacing XML?

For most common web service use cases today, JSON has largely replaced XML. The advantages of simplicity, compactness, and JSON being schema-less make it better suited for common data exchange. However, XML still has benefits for applications requiring more rigorous validation, querying, namespaces, and schemas.

  1. How do I pretty print JSON?

Online JSON formatters and linters can be used to format JSON with proper spacing and line breaks to make it more human-readable. Text editors can also reformat JSON. For readability, each JSON object or array should be printed on a new line.

Leave a Reply

Your email address will not be published. Required fields are marked *