JSON - Quick Guide (2024)

'; var adpushup = adpushup || {}; adpushup.que = adpushup.que || []; adpushup.que.push(function() { adpushup.triggerAd(ad_id); });

JSON or JavaScript Object Notation 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.

Characteristics of JSON

  • JSON is easy to read and write.
  • It is a lightweight text-based interchange format.
  • JSON is language independent.

Simple Example in JSON

The following example shows how to use JSON to store information related to books based on their topic and edition.

{ "book": [ { "id":"01", "language": "Java", "edition": "third", "author": "Herbert Schildt" }, { "id":"07", "language": "C++", "edition": "second", "author": "E.Balagurusamy" } ]}

After understanding the above program, we will try another example. Let's save the below code as json.htm

<html> <head> <title>JSON example</title> <script language = "javascript" > var object1 = { "language" : "Java", "author" : "herbert schildt" }; document.write("<h1>JSON with JavaScript example</h1>"); document.write("<br>"); document.write("<h3>Language = " + object1.language+"</h3>"); document.write("<h3>Author = " + object1.author+"</h3>"); var object2 = { "language" : "C++", "author" : "E-Balagurusamy" }; document.write("<br>"); document.write("<h3>Language = " + object2.language+"</h3>"); document.write("<h3>Author = " + object2.author+"</h3>"); document.write("<hr />"); document.write(object2.language + " programming language can be studied " + "from book written by " + object2.author); document.write("<hr />"); </script> </head> <body> </body></html>

Now let's try to open json.htm using IE or any other javascript enabled browser that produces the following result −

JSON - Quick Guide (2)

You can refer to JSON Objects chapter for more information on JSON objects.

Let's have a quick look at the basic syntax of JSON. JSON syntax is basically considered as a subset of JavaScript syntax; it includes the following −

  • Data is represented in name/value pairs.

  • Curly braces hold objects and each name is followed by ':'(colon), the name/value pairs are separated by , (comma).

  • Square brackets hold arrays and values are separated by ,(comma).

Below is a simple example −

{ "book": [ { "id": "01", "language": "Java", "edition": "third", "author": "Herbert Schildt" }, { "id": "07", "language": "C++", "edition": "second", "author": "E.Balagurusamy" } ]}

JSON supports the following two data structures −

  • Collection of name/value pairs − This Data Structure is supported by different programming languages.

  • Ordered list of values − It includes array, list, vector or sequence etc.

JSON format supports the following data types −

Sr.No.Type & Description
1

Number

double- precision floating-point format in JavaScript

2

String

double-quoted Unicode with backslash escaping

3

Boolean

true or false

4

Array

an ordered sequence of values

5

Value

it can be a string, a number, true or false, null etc

6

Object

an unordered collection of key:value pairs

7

Whitespace

can be used between any pair of tokens

8

null

empty

Number

The following table shows the number types −

Sr.No.Type & Description
1

Integer

Digits 1-9, 0 and positive or negative

2

Fraction

Fractions like .3, .9

3

Exponent

Exponent like e, e+, e-, E, E+, E-

Syntax

var json-object-name = { string : number_value, .......}

Example

Example showing Number Datatype, value should not be quoted −

var obj = {marks: 97}

String

  • It is a sequence of zero or more double quoted Unicode characters with backslash escaping.

  • Character is a single character string i.e. a string with length 1.

The table shows various special characters that you can use in strings of a JSON document −

Sr.No.Type & Description
1

"

double quotation

2

\

backslash

3

/

forward slash

4

b

backspace

5

f

form feed

6

n

new line

7

r

carriage return

8

t

horizontal tab

9

u

four hexadecimal digits

Syntax

var json-object-name = { string : "string value", .......}

Example

Example showing String Datatype −

var obj = {name: 'Amit'}

Boolean

It includes true or false values.

Syntax

var json-object-name = { string : true/false, .......}

Example

var obj = {name: 'Amit', marks: 97, distinction: true}

Array

  • It is an ordered collection of values.

  • These are enclosed in square brackets which means that array begins with .[. and ends with .]..

  • The values are separated by , (comma).

  • Array indexing can be started at 0 or 1.

  • Arrays should be used when the key names are sequential integers.

Syntax

[ value, .......]

Example

Example showing array containing multiple objects −

{ "books": [ { "language":"Java" , "edition":"second" }, { "language":"C++" , "lastName":"fifth" }, { "language":"C" , "lastName":"third" } ]}

Object

  • It is an unordered set of name/value pairs.

  • Objects are enclosed in curly braces that is, it starts with '{' and ends with '}'.

  • Each name is followed by ':'(colon) and the key/value pairs are separated by , (comma).

  • The keys must be strings and should be different from each other.

  • Objects should be used when the key names are arbitrary strings.

Syntax

{ string : value, .......}

Example

Example showing Object −

{ "id": "011A", "language": "JAVA", "price": 500,}

Whitespace

It can be inserted between any pair of tokens. It can be added to make a code more readable. Example shows declaration with and without whitespace −

Syntax

{string:" ",....}

Example

var obj1 = {"name": "Sachin Tendulkar"}var obj2 = {"name": "SauravGanguly"}

null

It means empty type.

Syntax

null

Example

var i = null;if(i == 1) { document.write("<h1>value is 1</h1>");} else { document.write("<h1>value is null</h1>");}

JSON Value

It includes −

  • number (integer or floating point)
  • string
  • boolean
  • array
  • object
  • null

Syntax

String | Number | Object | Array | TRUE | FALSE | NULL

Example

var i = 1;var j = "sachin";var k = null;

Creating Simple Objects

JSON objects can be created with JavaScript. Let us see the various ways of creating JSON objects using JavaScript −

  • Creation of an empty Object −
var JSONObj = {};
  • Creation of a new Object −
var JSONObj = new Object();
  • Creation of an object with attribute bookname with value in string, attribute price with numeric value. Attribute is accessed by using '.' Operator −

var JSONObj = { "bookname ":"VB BLACK BOOK", "price":500 };

This is an example that shows creation of an object in javascript using JSON, save the below code as json_object.htm

<html> <head> <title>Creating Object JSON with JavaScript</title> <script language = "javascript" > var JSONObj = { "name" : "tutorialspoint.com", "year" : 2005 }; document.write("<h1>JSON with JavaScript example</h1>"); document.write("<br>"); document.write("<h3>Website Name = "+JSONObj.name+"</h3>"); document.write("<h3>Year = "+JSONObj.year+"</h3>"); </script> </head> <body> </body></html>

Now let's try to open Json Object using IE or any other javaScript enabled browser. It produces the following result −

JSON - Quick Guide (3)

Creating Array Objects

The following example shows creation of an array object in javascript using JSON, save the below code as json_array_object.htm

<html> <head> <title>Creation of array object in javascript using JSON</title> <script language = "javascript" > document.writeln("<h2>JSON array object</h2>"); var books = { "Pascal" : [ { "Name" : "Pascal Made Simple", "price" : 700 }, { "Name" : "Guide to Pascal", "price" : 400 }], "Scala" : [ { "Name" : "Scala for the Impatient", "price" : 1000 }, { "Name" : "Scala in Depth", "price" : 1300 }] } var i = 0 document.writeln("<table border = '2'><tr>"); for(i = 0;i<books.Pascal.length;i++) { document.writeln("<td>"); document.writeln("<table border = '1' width = 100 >"); document.writeln("<tr><td><b>Name</b></td><td width = 50>" + books.Pascal[i].Name+"</td></tr>"); document.writeln("<tr><td><b>Price</b></td><td width = 50>" + books.Pascal[i].price +"</td></tr>"); document.writeln("</table>"); document.writeln("</td>"); } for(i = 0;i<books.Scala.length;i++) { document.writeln("<td>"); document.writeln("<table border = '1' width = 100 >"); document.writeln("<tr><td><b>Name</b></td><td width = 50>" + books.Scala[i].Name+"</td></tr>"); document.writeln("<tr><td><b>Price</b></td><td width = 50>" + books.Scala[i].price+"</td></tr>"); document.writeln("</table>"); document.writeln("</td>"); } document.writeln("</tr></table>"); </script> </head> <body> </body></html>

Now let's try to open Json Array Object using IE or any other javaScript enabled browser. It produces the following result −

JSON - Quick Guide (4)

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.

LanguagesLibraries
CWJElement (LGPLv3)
Javajson-schema-validator (LGPLv3)
.NETJson.NET (MIT)
ActionScript 3Frigga (MIT)
Haskellaeson-schema (MIT)
PythonJsonschema
Rubyautoparse (ASL 2.0); ruby-jsonschema (MIT)
PHPphp-json-schema (MIT). json-schema (Berkeley)
JavaScriptOrderly (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 −

Sr.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.

You can check a http://json-schema.org for the complete list of keywords that can be used in defining a JSON schema. The above schema can be used to test the validity of the following JSON code −

[ { "id": 2, "name": "An ice sculpture", "price": 12.50, }, { "id": 3, "name": "A blue mouse", "price": 25.50, }]

JSON and XML are human readable formats and are language independent. They both have support for creation, reading and decoding in real world situations. We can compare JSON with XML, based on the following factors −

Verbose

XML is more verbose than JSON, so it is faster to write JSON for programmers.

Arrays Usage

XML is used to describe the structured data, which doesn't include arrays whereas JSON include arrays.

Parsing

JavaScript's eval method parses JSON. When applied to JSON, eval returns the described object.

Example

Individual examples of XML and JSON −

JSON

{ "company": Volkswagen, "name": "Vento", "price": 800000}

XML

<car> <company>Volkswagen</company> <name>Vento</name> <price>800000</price></car>

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

Environment

As of PHP 5.2.0, the JSON extension is bundled and compiled into PHP by default.

JSON Functions

FunctionLibraries
json_encodeReturns the JSON representation of a value.
json_decodeDecodes a JSON string.
json_last_errorReturns the last error occurred.

Encoding JSON in PHP (json_encode)

PHP json_encode() function is used for encoding JSON in PHP. This function returns the JSON representation of a value on success or FALSE on failure.

Syntax

string json_encode ( $value [, $options = 0 ] )

Parameters

  • value − The value being encoded. This function only works with UTF-8 encoded data.

  • options − This optional value is a bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT.

Example

The following example shows how to convert an array into JSON with PHP −

<?php $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); echo json_encode($arr);?>

While executing, this will produce the following result −

{"a":1,"b":2,"c":3,"d":4,"e":5}

The following example shows how the PHP objects can be converted into JSON −

<?php class Emp { public $name = ""; public $hobbies = ""; public $birthdate = ""; } $e = new Emp(); $e->name = "sachin"; $e->hobbies = "sports"; $e->birthdate = date('m/d/Y h:i:s a', "8/5/1974 12:20:03 p"); $e->birthdate = date('m/d/Y h:i:s a', strtotime("8/5/1974 12:20:03")); echo json_encode($e);?>

While executing, this will produce the following result −

{"name":"sachin","hobbies":"sports","birthdate":"08\/05\/1974 12:20:03 pm"}

Decoding JSON in PHP (json_decode)

PHP json_decode() function is used for decoding JSON in PHP. This function returns the value decoded from json to appropriate PHP type.

Syntax

mixed json_decode ($json [,$assoc = false [, $depth = 512 [, $options = 0 ]]])

Paramaters

  • json_string − It is an encoded string which must be UTF-8 encoded data.

  • assoc − It is a boolean type parameter, when set to TRUE, returned objects will be converted into associative arrays.

  • depth − It is an integer type parameter which specifies recursion depth

  • options − It is an integer type bitmask of JSON decode, JSON_BIGINT_AS_STRING is supported.

Example

The following example shows how PHP can be used to decode JSON objects −

<?php $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; var_dump(json_decode($json)); var_dump(json_decode($json, true));?>

While executing, it will produce the following result −

object(stdClass)#1 (5) { ["a"] => int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5)}array(5) { ["a"] => int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5)}

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

Environment

Before you start encoding and decoding JSON using Perl, you need to install JSON module, which can be obtained from CPAN. Once you downloaded JSON-2.53.tar.gz or any other latest version, follow the steps mentioned below −

$tar xvfz JSON-2.53.tar.gz$cd JSON-2.53$perl Makefile.PL$make$make install

JSON Functions

FunctionLibraries
encode_jsonConverts the given Perl data structure to a UTF-8 encoded, binary string.
decode_jsonDecodes a JSON string.
to_jsonConverts the given Perl data structure to a json string.
from_jsonExpects a json string and tries to parse it, returning the resulting reference.
convert_blessedUse this function with true value so that Perl can use TO_JSON method on the object's class to convert an object into JSON.

Encoding JSON in Perl (encode_json)

Perl encode_json() function converts the given Perl data structure to a UTF-8 encoded, binary string.

Syntax

$json_text = encode_json ($perl_scalar );or$json_text = JSON->new->utf8->encode($perl_scalar);

Example

The following example shows arrays under JSON with Perl −

#!/usr/bin/perluse JSON;my %rec_hash = ('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);my $json = encode_json \%rec_hash;print "$json\n";

While executing, this will produce the following result −

{"e":5,"c":3,"a":1,"b":2,"d":4}

The following example shows how Perl objects can be converted into JSON −

#!/usr/bin/perlpackage Emp;sub new { my $class = shift; my $self = { name => shift, hobbies => shift, birthdate => shift, }; bless $self, $class; return $self;}sub TO_JSON { return { %{ shift() } }; }package main;use JSON;my $JSON = JSON->new->utf8;$JSON->convert_blessed(1);$e = new Emp( "sachin", "sports", "8/5/1974 12:20:03 pm");$json = $JSON->encode($e);print "$json\n";

On executing, it will produce the following result −

{"birthdate":"8/5/1974 12:20:03 pm","name":"sachin","hobbies":"sports"}

Decoding JSON in Perl (decode_json)

Perl decode_json() function is used for decoding JSON in Perl. This function returns the value decoded from json to an appropriate Perl type.

Syntax

$perl_scalar = decode_json $json_textor$perl_scalar = JSON->new->utf8->decode($json_text)

Example

The following example shows how Perl can be used to decode JSON objects. Here you will need to install Data::Dumper module if you already do not have it on your machine.

#!/usr/bin/perluse JSON;use Data::Dumper;$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';$text = decode_json($json);print Dumper($text);

On executing, it will produce following result −

$VAR1 = { 'e' => 5, 'c' => 3, 'a' => 1, 'b' => 2, 'd' => 4};

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

Environment

Before you start with encoding and decoding JSON using Python, you need to install any of the JSON modules available. For this tutorial we have downloaded and installed Demjson as follows −

$tar xvfz demjson-1.6.tar.gz$cd demjson-1.6$python setup.py install

JSON Functions

FunctionLibraries
encodeEncodes the Python object into a JSON string representation.
decodeDecodes a JSON-encoded string into a Python object.

Encoding JSON in Python (encode)

Python encode() function encodes the Python object into a JSON string representation.

Syntax

demjson.encode(self, obj, nest_level=0)

Example

The following example shows arrays under JSON with Python.

#!/usr/bin/pythonimport demjsondata = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]json = demjson.encode(data)print json

While executing, this will produce the following result −

[{"a":1,"b":2,"c":3,"d":4,"e":5}]

Decoding JSON in Python (decode)

Python can use demjson.decode() function for decoding JSON. This function returns the value decoded from json to an appropriate Python type.

Syntax

demjson.decode(self, txt)

Example

The following example shows how Python can be used to decode JSON objects.

#!/usr/bin/pythonimport demjsonjson = '{"a":1,"b":2,"c":3,"d":4,"e":5}';text = demjson.decode(json)print text

On executing, it will produce the following result −

{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}

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

Environment

Before you start with encoding and decoding JSON using Ruby, you need to install any of the JSON modules available for Ruby. You may need to install Ruby gem, but if you are running latest version of Ruby then you must have gem already installed on your machine, otherwise let's follow the following single step assuming you already have gem installed −

$gem install json

Parsing JSON using Ruby

The following example shows that the first 2 keys hold string values and the last 3 keys hold arrays of strings. Let's keep the following content in a file called input.json.

{ "President": "Alan Isaac", "CEO": "David Richardson", "India": [ "Sachin Tendulkar", "Virender Sehwag", "Gautam Gambhir" ], "Srilanka": [ "Lasith Malinga", "Angelo Mathews", "Kumar Sangakkara" ], "England": [ "Alastair Cook", "Jonathan Trott", "Kevin Pietersen" ]}

Given below is a Ruby program that will be used to parse the above mentioned JSON document −

#!/usr/bin/rubyrequire 'rubygems'require 'json'require 'pp'json = File.read('input.json')obj = JSON.parse(json)pp obj

On executing, it will produce the following result −

{ "President"=>"Alan Isaac", "CEO"=>"David Richardson", "India"=> ["Sachin Tendulkar", "Virender Sehwag", "Gautam Gambhir"], "Srilanka"=> ["Lasith Malinga ", "Angelo Mathews", "Kumar Sangakkara"], "England"=> ["Alastair Cook", "Jonathan Trott", "Kevin Pietersen"]}

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.

JSONJava
stringjava.lang.String
numberjava.lang.Number
true|falsejava.lang.Boolean
nullnull
arrayjava.util.List
objectjava.util.Map

On decoding, the default concrete class of java.util.List is org.json.simple.JSONArray and the default concrete class of java.util.Map is org.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 and JSONArray where JSONObject is a java.util.Map and JSONArray is a java.util.List, so you can access them with standard operations of Map or List.

import org.json.simple.JSONObject;import org.json.simple.JSONArray;import org.json.simple.parser.ParseException;import org.json.simple.parser.JSONParser;class JsonDecodeDemo { public static void main(String[] args) { JSONParser parser = new JSONParser(); String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]"; try{ Object obj = parser.parse(s); JSONArray array = (JSONArray)obj; System.out.println("The 2nd element of array"); System.out.println(array.get(1)); System.out.println(); JSONObject obj2 = (JSONObject)array.get(1); System.out.println("Field \"1\""); System.out.println(obj2.get("1")); s = "{}"; obj = parser.parse(s); System.out.println(obj); s = "[5,]"; obj = parser.parse(s); System.out.println(obj); s = "[5,,2]"; obj = parser.parse(s); System.out.println(obj); }catch(ParseException pe) { System.out.println("position: " + pe.getPosition()); System.out.println(pe); } }}

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

The 2nd element of array{"1":{"2":{"3":{"4":[5,{"6":7}]}}}}Field "1"{"2":{"3":{"4":[5,{"6":7}]}}}{}[5][5,2]

AJAX is Asynchronous JavaScript and XML, which is used on the client side as a group of interrelated web development techniques, in order to create asynchronous web applications. According to the AJAX model, web applications can send and retrieve data from a server asynchronously without interfering with the display and the behavior of the existing page.

Many developers use JSON to pass AJAX updates between the client and the server. Websites updating live sports scores can be considered as an example of AJAX. If these scores have to be updated on the website, then they must be stored on the server so that the webpage can retrieve the score when it is required. This is where we can make use of JSON formatted data.

Any data that is updated using AJAX can be stored using the JSON format on the web server. AJAX is used so that javascript can retrieve these JSON files when necessary, parse them, and perform one of the following operations −

  • Store the parsed values in the variables for further processing before displaying them on the webpage.

  • It directly assigns the data to the DOM elements in the webpage, so that they are displayed on the website.

Example

The following code shows JSON with AJAX. Save it as ajax.htm file. Here the loading function loadJSON() is used asynchronously to upload JSON data.

<html> <head> <meta content = "text/html; charset = ISO-8859-1" http-equiv = "content-type"> <script type = "application/javascript"> function loadJSON() { var data_file = "http://www.tutorialspoint.com/json/data.json"; var http_request = new XMLHttpRequest(); try{ // Opera 8.0+, Firefox, Chrome, Safari http_request = new XMLHttpRequest(); }catch (e) { // Internet Explorer Browsers try{ http_request = new ActiveXObject("Msxml2.XMLHTTP"); }catch (e) { try{ http_request = new ActiveXObject("Microsoft.XMLHTTP"); }catch (e) { // Something went wrong alert("Your browser broke!"); return false; } } } http_request.onreadystatechange = function() { if (http_request.readyState == 4 ) { // Javascript function JSON.parse to parse JSON data var jsonObj = JSON.parse(http_request.responseText); // jsonObj variable now contains the data structure and can // be accessed as jsonObj.name and jsonObj.country. document.getElementById("Name").innerHTML = jsonObj.name; document.getElementById("Country").innerHTML = jsonObj.country; } } http_request.open("GET", data_file, true); http_request.send(); } </script> <title>tutorialspoint.com JSON</title> </head> <body> <h1>Cricketer Details</h1> <table class = "src"> <tr><th>Name</th><th>Country</th></tr> <tr><td><div id = "Name">Sachin</div></td> <td><div id = "Country">India</div></td></tr> </table> <div class = "central"> <button type = "button" onclick = "loadJSON()">Update Details </button> </div> </body></html>

Given below is the input file data.json, having data in JSON format which will be uploaded asynchronously when we click the Update Detail button. This file is being kept in http://www.tutorialspoint.com/json/

{"name": "Brett", "country": "Australia"}

The above HTML code will generate the following screen, where you can check AJAX in action −

NameCountry

Sachin

India

When you click on the Update Detail button, you should get a result something as follows. You can try JSON with AJAX yourself, provided your browser supports Javascript.

NameCountry

Brett

Australia

Advertisem*nts

';adpushup.triggerAd(ad_id); });

JSON - Quick Guide (2024)

FAQs

Is JSON hard to learn? ›

JSON is not particularly hard to use because there aren't many prerequisites to using it. It's human-readable which makes it fairly accessible to even novice developers. JSON also has relatively few data types you need to know before you're able to use it, so it can be relatively easy to get started using JSON.

What is JSON and how to use it? ›

JSON is a file format that uses human-readable language to store and communicate data objects. JSON (JavaScript Object Notation) is defined as a file format used in object-oriented programming that uses human-readable language, text, and syntax to store and communicate data objects between applications.

Is JSON easy to use? ›

JSON (JavaScript Object Notation) is commonly used for data storage and transfer. JSON is a popular choice for applications that benefit from a simple and easy-to-use data format. XML (Extensible Markup Language) is a general-purpose markup language similar to JSON that allows for more complex data structures.

How to quickly format JSON? ›

You can format your JSON document using Ctrl+Shift+I or Format Document from the context menu.

Is JSON becoming obsolete? ›

JSON is undeniably here to stay. With JavaScript as the most widely used development platform today, JSON has become the most prominent data interchange format. For small projects with low complexity, JSON is a perfect fit.

Why is JSON better than SQL? ›

Easier Maintenance: When using JSON data, developers don't have to do hard-core coding for setting configurations. Simply store it in a JSON file; that's it, and then it will load the setting dynamically. This way, developers can easily customize the application and maintain it.

Why is JSON so popular? ›

JSON is popular with developers because it's a flexible format for data exchange that enjoys wide support in modern programming languages and software systems. It's text based and lightweight and has an easy-to-parse data format, meaning it requires no additional code to understand and interpret the data provided.

What is a JSON file for dummies? ›

JSON allows developers to store various data types as human-readable code, with the keys serving as names and the values containing related data. JSON syntax is derived from JavaScript object notation syntax: Data is in key/value pairs. Data is separated by commas.

What is a common use of JSON? ›

A common use of JSON is to read data from a web server, and display the data in a web page. For simplicity, this can be demonstrated using a string as input.

What is JSON in layman's terms? ›

JSON (JavaScript Object Notation) is a text-based, human-readable data interchange format used to exchange data between web clients and web servers. The format defines a set of structuring rules for the representation of structured data.

Do people still use JSON? ›

Additionally, both formats are self-describing, so you can read and edit JSON and XML files in any text editor. Although XML is an older technology, both JSON and XML are still commonly used.

Is there something better than JSON? ›

Both JSON and CSV are popular because of their simplicity. It makes them easy to use in any environment. CSV is more limited since it only supports tabular data. But on the other hand, it is a more concise format than JSON.

What does JSON look like? ›

A JSON object contains zero, one, or more key-value pairs, also called properties. The object is surrounded by curly braces {} . Every key-value pair is separated by a comma. The order of the key-value pair is irrelevant.

How to read a JSON? ›

Reading JSON

To read JSON data, you can use the built-in json module (JSON Encoder and Decoder) in Python. The json module provides two methods, loads and load, that allow you to parse JSON strings and JSON files, respectively, to convert JSON into Python objects such as lists and dictionaries.

What is a JSON file used for? ›

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).

Should I learn JSON or Python? ›

Python supports a wider range of data types such as lists, tuples, sets, and more, whereas JSON has a more limited set of data types, mainly consisting of strings, numbers, booleans, arrays, and objects. Python's broader range of data types allows for more versatile and complex data structures.

How much do JSON programmers make? ›

Json Developer Salary
Annual SalaryHourly Wage
Top Earners$150,500$72
75th Percentile$134,500$65
Average$109,905$53
25th Percentile$84,000$40

Should I learn JSON or XML? ›

If you want to store several different data types with many variables, then XML is the better choice. XML checks for errors in complex data more efficiently than JSON, as XML focuses on storing data in a machine-readable way. It also has a more mature set of tools and libraries and may work better with legacy systems.

Is JSON considered coding? ›

Many people think of JSON (JavaScript Object Notation) as a language, but it's really just a data interchange format that works natively with most modern languages, like Python, Java, PHP, and JavaScript. JSON is commonly used for transmitting data in web applications.

Top Articles
An Inaccurate Bill of Lading Can Put You at Risk
What Happens if You Try to Cash a Bad Check?
Hotels Near 6491 Peachtree Industrial Blvd
The Largest Banks - ​​How to Transfer Money With Only Card Number and CVV (2024)
Brady Hughes Justified
Occupational therapist
Practical Magic 123Movies
Jesus Calling December 1 2022
Pickswise the Free Sports Handicapping Service 2023
Tribune Seymour
Garrick Joker'' Hastings Sentenced
Top Hat Trailer Wiring Diagram
Craigslist Jobs Phoenix
Thotsbook Com
Trini Sandwich Crossword Clue
Dr. med. Uta Krieg-Oehme - Lesen Sie Erfahrungsberichte und vereinbaren Sie einen Termin
Teenleaks Discord
Brett Cooper Wikifeet
Inside the life of 17-year-old Charli D'Amelio, the most popular TikTok star in the world who now has her own TV show and clothing line
Palm Springs Ca Craigslist
MLB power rankings: Red-hot Chicago Cubs power into September, NL wild-card race
Lista trofeów | Jedi Upadły Zakon / Fallen Order - Star Wars Jedi Fallen Order - poradnik do gry | GRYOnline.pl
Lowes Undermount Kitchen Sinks
Scout Shop Massapequa
Busted Mcpherson Newspaper
Morse Road Bmv Hours
Www.paystubportal.com/7-11 Login
T Mobile Rival Crossword Clue
Shoe Station Store Locator
Criterion Dryer Review
What Sells at Flea Markets: 20 Profitable Items
Unity Webgl Car Tag
Ullu Coupon Code
Keshi with Mac Ayres and Starfall (Rescheduled from 11/1/2024) (POSTPONED) Tickets Thu, Nov 1, 2029 8:00 pm at Pechanga Arena - San Diego in San Diego, CA
Restored Republic
Mia Malkova Bio, Net Worth, Age & More - Magzica
47 Orchid Varieties: Different Types of Orchids (With Pictures)
Serenity Of Lathrop - Manteca Photos
Gwu Apps
Craigslist Georgia Homes For Sale By Owner
Myanswers Com Abc Resources
Pokemon Reborn Locations
Wo ein Pfand ist, ist auch Einweg
This 85-year-old mom co-signed her daughter's student loan years ago. Now she fears the lender may take her house
Mbfs Com Login
Toomics - Die unendliche Welt der Comics online
20 Mr. Miyagi Inspirational Quotes For Wisdom
RubberDucks Front Office
This Doctor Was Vilified After Contracting Ebola. Now He Sees History Repeating Itself With Coronavirus
Ups Customer Center Locations
Craigslist Farm And Garden Missoula
Wayward Carbuncle Location
Latest Posts
Article information

Author: Eusebia Nader

Last Updated:

Views: 5969

Rating: 5 / 5 (80 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Eusebia Nader

Birthday: 1994-11-11

Address: Apt. 721 977 Ebert Meadows, Jereville, GA 73618-6603

Phone: +2316203969400

Job: International Farming Consultant

Hobby: Reading, Photography, Shooting, Singing, Magic, Kayaking, Mushroom hunting

Introduction: My name is Eusebia Nader, I am a encouraging, brainy, lively, nice, famous, healthy, clever person who loves writing and wants to share my knowledge and understanding with you.