Blog about Programming Languages & Coding

Blog about Programming Languages & Coding
Contents for Computer Science, IT, B.Sc. CS & IT, M.Sc. CS & IT, MCA, BE CS & IT, ME CS & IT , Interview Questions, Books and Online Course Recommendations from Udemy, Coursera, etc

JSON

JSON (JavaScript Object Notation)




JSON is a lightweight text-based open standard designed for human-readable data interchange. Conventions used by JSON are known to programmers, which include C, C++, Java, Python, Perl, etc.

  • JSON stands for JavaScript Object Notation.

  • The format was specified by Douglas Crockford.

  • It was designed for human-readable data interchange.

  • It has been extended from the JavaScript scripting language.

  • The filename extension is .json.

  • JSON Internet Media type is application/json.

  • The Uniform Type Identifier is public.json.

Uses of JSON

  • It is used while writing JavaScript based applications that includes browser extensions and websites.

  • JSON format is used for serializing and transmitting structured data over network connection.

  • It is primarily used to transmit data between a server and web applications.

  • Web services and APIs use JSON format to provide public data.

  • It can be used with modern programming languages.

Features of JSON

  1. Simplicity

  2. Openness

  3. Self Describing

  4. Internationalization

  5. Extensibility

  6. Interoperability

Exchanging Data

When exchanging data between a browser and a server, the data can only be text.

JSON is text, and we can convert any JavaScript object into JSON, and send JSON to the server.

We can also convert any JSON received from the server into JavaScript objects.

This way we can work with the data as JavaScript objects, with no complicated parsing and translations.

Sending Data

If you have data stored in a JavaScript object, you can convert the object into JSON, and send it to a server:

Example

var myObj = "name":"John""age":31"city":"New York" };
var myJSON = JSON.stringify(myObj);
window.location = "demo_json.php?x=" + myJSON;

Receiving Data

If you receive data in JSON format, you can convert it into a JavaScript object:

Example

var myJSON = '{ "name":"John", "age":31, "city":"New York" }';
var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.name;

Storing Data

When storing data, the data has to be a certain format, and regardless of where you choose to store it, text is always one of the legal formats.

JSON makes it possible to store JavaScript objects as text.

Example

Storing data in local storage

//Storing data:
myObj = "name":"John""age":31"city":"New York" };
myJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);

//Retrieving data:
text = localStorage.getItem("testJSON");
obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.name;

JSON Syntax

The JSON syntax is a subset of the JavaScript syntax.

JSON Syntax Rules

JSON syntax is derived from JavaScript object notation syntax:

  • Data is in name/value pairs

  • Data is separated by commas

  • Curly braces hold objects

  • Square brackets hold arrays

JSON Data - A Name and a Value

JSON data is written as name/value pairs.

A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value:

Example

"name":"John"

JSON names require double quotes. JavaScript names don't.

JSON - Evaluates to JavaScript Objects

The JSON format is almost identical to JavaScript objects.

In JSON, keys must be strings, written with double quotes:

JSON

"name":"John" }

In JavaScript, keys can be strings, numbers, or identifier names:

JavaScript

{ name:"John" }

JSON Values

In JSON, values must be one of the following data types:

  • a string

  • a number

  • an object (JSON object)

  • an array

  • a boolean

  • null

In JavaScript values can be all of the above, plus any other valid JavaScript expression, including:

  • a function

  • a date

  • undefined

In JSON, string values must be written with double quotes:

JSON

"name":"John" }
In JavaScript, you can write string values with double or single quotes:

JavaScript

{ name:'John' }

JSON Uses JavaScript Syntax

Because JSON syntax is derived from JavaScript object notation, very little extra software is needed to work with JSON within JavaScript.

With JavaScript you can create an object and assign data to it, like this:

Example

var person = "name":"John""age":31"city":"New York" };

You can access a JavaScript object like this:

Example

// returns John
person.name;

It can also be accessed like this:

Example

// returns John
person["name"];

Data can be modified like this:

Example

person.name = "Gilbert";

It can also be modified like this:

Example

person["name"] = "Gilbert";

You will learn how to convert JavaScript objects into JSON later in this tutorial.

JavaScript Arrays as JSON

The same way JavaScript objects can be used as JSON, JavaScript arrays can also be used as JSON.

You will learn more about arrays as JSON later in this tutorial.

JSON Files

  • The file type for JSON files is ".json"

  • The MIME type for JSON text is "application/json"

JSON Data Types

In JSON, values must be one of the following data types:

  • a string

  • a number

  • an object (JSON object)

  • an array

  • a boolean

  • null

JSON values cannot be one of the following data types:

  • a function

  • a date

  • undefined

JSON Strings

Strings in JSON must be written in double quotes.

Example

"name":"John" }

JSON Numbers

Numbers in JSON must be an integer or a floating point.

Example

"age":30 }

JSON Objects

Values in JSON can be objects.

Example

{
"employee":{ "name":"John""age":30"city":"New York" }
}

Objects as values in JSON must follow the same rules as JSON objects.

JSON Arrays

Values in JSON can be arrays.

Example

{
"employees":[ "John""Anna""Peter" ]
}

JSON Booleans

Values in JSON can be true/false.

Example

"sale":true }

JSON null

Values in JSON can be null.

Example

"middlename":null }

JSON Objects

Object Syntax

Example

"name":"John""age":30"car":null }

JSON objects are surrounded by curly braces {}.

JSON objects are written in key/value pairs.

Keys must be strings, and values must be a valid JSON data type (string, number, object, array, boolean or null).

Keys and values are separated by a colon.

Each key/value pair is separated by a comma.

Accessing Object Values

You can access the object values by using dot (.) notation:

Example

myObj = "name":"John""age":30"car":null };
x = myObj.name;
You can also access the object values by using bracket ([]) notation:

Example

myObj = "name":"John""age":30"car":null };
x = myObj["name"];

JSON Arrays

Arrays as JSON Objects

Example

"Ford""BMW""Fiat" ]

Arrays in JSON are almost the same as arrays in JavaScript.

In JSON, array values must be of type string, number, object, array, boolean or null.

In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.

Arrays in JSON Objects

Arrays can be values of an object property:

Example

{
"name":"John",
"age":30,
"cars":[ "Ford""BMW""Fiat" ]
}

Accessing Array Values

You access the array values by using the index number:

Example

x = myObj.cars[0];
Looping Through an Array

You can access array values by using a for-in loop:

Example

for (i in myObj.cars) {
    x += myObj.cars[i];
}

JSON vs XML

The following JSON and XML examples both defines an employees object, with an array of 3 employees:

JSON Example

{"employees":[
    { "firstName":"John""lastName":"Doe" },
    { "firstName":"Anna""lastName":"Smith" },
    { "firstName":"Peter""lastName":"Jones" }
]}

XML Example

<employees>
    <employee>
        <firstName>John</firstName> <lastName>Doe</lastName>
    </employee>
    <employee>
        <firstName>Anna</firstName> <lastName>Smith</lastName>
    </employee>
    <employee>
        <firstName>Peter</firstName> <lastName>Jones</lastName>
    </employee>
</employees>

A list of differences between JSON and XML are given below.

No.

JSON

XML

1)

JSON stands for JavaScript Object Notation.

XML stands for eXtensible Markup Language.

2)

JSON is simple to read and write.

XML is less simple than JSON.

3)

JSON is easy to learn.

XML is less easy than JSON.

4)

JSON is data-oriented.

XML is document-oriented.

5)

JSON doesn't provide display capabilities.

XML provides the capability to display data because it is a markup language.

6)

JSON supports array.

XML doesn't support array.

7)

JSON is less secured than XML.

XML is more secured.

8)

JSON files are more human readable than XML.

XML files are less human readable.

9)

JSON supports only text and number data type.

XML support many data types such as text, number, images, charts, graphs etc. Moreover, XML offeres options for transferring the format or structure of the data with actual data.

Similarities between JSON and XML

  • Both are simple and open.

  • Both supports unicode. So internationalization is supported by JSON and XML both.

  • Both represents self describing data.

  • Both are interoperable or language-independent.

Why JSON is Better Than XML

XML is much more difficult to parse than JSON.
JSON is parsed into a ready-to-use JavaScript object.

For AJAX applications, JSON is faster and easier than XML:

Using XML

  • Fetch an XML document

  • Use the XML DOM to loop through the document

  • Extract values and store in variables

Using JSON

  • Fetch a JSON string

  • JSON.Parse the JSON string

JSON - Schema

JSON Schema is a specification for JSON based format for defining the structure of JSON data. It was written under IETF draft which expired in 2011. JSON Schema −

  • Describes your existing data format.

  • Clear, human- and machine-readable documentation.

  • Complete structural validation, useful for automated testing.

  • Complete structural validation, validating client-submitted data.

JSON Schema Validation Libraries

There are several validators currently available for different programming languages. Currently the most complete and compliant JSON Schema validator available is JSV.

Languages

Libraries

C

WJElement (LGPLv3)

Java

json-schema-validator (LGPLv3)

.NET

Json.NET (MIT)

ActionScript 3

Frigga (MIT)

Haskell

aeson-schema (MIT)

Python

Jsonschema

Ruby

autoparse (ASL 2.0); ruby-jsonschema (MIT)

PHP

php-json-schema (MIT). json-schema (Berkeley)

JavaScript

Orderly (BSD); JSV; json-schema; Matic (MIT); Dojo; Persevere (modified BSD or AFL 2.0); schema.js.

JSON Schema Example

Given below is a basic JSON schema, which covers a classical product catalog description −

{

   "$schema": "http://json-schema.org/draft-04/schema#",

   "title": "Product",

   "description": "A product from Acme's catalog",

   "type": "object",

   "properties": {

      "id": {

         "description": "The unique identifier for a product",

         "type": "integer"

      },

      "name": {

         "description": "Name of the product",

         "type": "string"

      },

      "price": {

         "type": "number",

         "minimum": 0,

         "exclusiveMinimum": true

      }

   },

   "required": ["id", "name", "price"]

}

Let's the check various important keywords that can be used in this schema −

S. No.

Keyword & Description

1

$schema

The $schema keyword states that this schema is written according to the draft v4 specification.

2

title

You will use this to give a title to your schema.

3

description

A little description of the schema.

4

type

The type keyword defines the first constraint on our JSON data: it has to be a JSON Object.

5

properties

Defines various keys and their value types, minimum and maximum values to be used in JSON file.

6

required

This keeps a list of required properties.

7

minimum

This is the constraint to be put on the value and represents minimum acceptable value.

8

exclusiveMinimum

If "exclusiveMinimum" is present and has boolean value true, the instance is valid if it is strictly greater than the value of "minimum".

9

maximum

This is the constraint to be put on the value and represents maximum acceptable value.

10

exclusiveMaximum

If "exclusiveMaximum" is present and has boolean value true, the instance is valid if it is strictly lower than the value of "maximum".

11

multipleOf

A numeric instance is valid against "multipleOf" if the result of the division of the instance by this keyword's value is an integer.

12

maxLength

The length of a string instance is defined as the maximum number of its characters.

13

minLength

The length of a string instance is defined as the minimum number of its characters.

14

pattern

A string instance is considered valid if the regular expression matches the instance successfully.

JSON with Java

This chapter covers how to encode and decode JSON objects using Java programming language. Let's start with preparing the environment to start our programming with Java for JSON.

Environment

Before you start with encoding and decoding JSON using Java, you need to install any of the JSON modules available. For this tutorial we have downloaded and installed JSON.simple and have added the location of json-simple-1.1.1.jar file to the environment variable CLASSPATH.

Mapping between JSON and Java entities

JSON.simple maps entities from the left side to the right side while decoding or parsing, and maps entities from the right to the left while encoding.

JSON

Java

string

java.lang.String

number

java.lang.Number

true|false

java.lang.Boolean

null

null

array

java.util.List

object

java.util.Map

On decoding, the default concrete class of java.util.List isorg.json.simple.JSONArray and the default concrete class of java.util.Map isorg.json.simple.JSONObject.

Encoding JSON in Java

Following is a simple example to encode a JSON object using Java JSONObject which is a subclass of java.util.HashMap. No ordering is provided. If you need the strict ordering of elements, use JSONValue.toJSONString ( map ) method with ordered map implementation such as java.util.LinkedHashMap.


import org.json.simple.JSONObject;

class JsonEncodeDemo {


   public static void main(String[] args){

      JSONObject obj = new JSONObject();


      obj.put("name", "foo");

      obj.put("num", new Integer(100));

      obj.put("balance", new Double(1000.21));

      obj.put("is_vip", new Boolean(true));


      System.out.print(obj);

   }

}

On compiling and executing the above program the following result will be generated −

{"balance": 1000.21, "num":100, "is_vip":true, "name":"foo"}

Following is another example that shows a JSON object streaming using Java JSONObject −

import org.json.simple.JSONObject;


class JsonEncodeDemo {


   public static void main(String[] args){

      JSONObject obj = new JSONObject();


      obj.put("name","foo");

      obj.put("num",new Integer(100));

      obj.put("balance",new Double(1000.21));

      obj.put("is_vip",new Boolean(true));


      StringWriter out = new StringWriter();

      obj.writeJSONString(out);

      

      String jsonText = out.toString();

      System.out.print(jsonText);

   }

}

On compiling and executing the above program, the following result is generated −

{"balance": 1000.21, "num":100, "is_vip":true, "name":"foo"}

Decoding JSON in Java

The following example makes use of JSONObject 

import org.json.simple.JSONObject;  

import org.json.simple.JSONValue;  

public class JsonDecode {  

public static void main(String[] args) {  

    String s="{\"name\":\"sycs\",\"salary\":600000.0,\"age\":27}";  

    Object obj=JSONValue.parse(s);  

    JSONObject jsonObject = (JSONObject) obj;  

  

    String name = (String) jsonObject.get("name");  

    double salary = (Double) jsonObject.get("salary");  

    long age = (Long) jsonObject.get("age");  

    System.out.println(name+" "+salary+" "+age);  

}  

}  


JSON JSON Reviewed by Asst. Prof. Sunita Rai on March 27, 2022 Rating: 5

No comments:

Powered by Blogger.