JSON Best Tutorial

http://www.xappsoftware.com/wordpress/wp-content/uploads/2014/02/json_logo-555px.png

http://www.w3resource.com/JSON/introduction.php

What is JSON

JSON is a lightweight text-based open standard data-interchange format. It is human readable. JSON is derived from a subset of JavaScript programming language (Standard ECMA-262 3rd Edition—December 1999). It is entirely language independent and can be used with most of the modern programming languages.
JSON is often used to serialize and transfer data over a network connection, for example between web server and a web application. In computer science, serialization is a process to transforming data structures and objects in a format suitable to be stored in a file or memory buffer or transmitted over a network connection. Later on, this data can be retrieved. Because of the very nature of the JSON, it is useful for storing or representing semi structured data
JSON is a standard and is specified on RFC4627 on IETF (International Engineering Task Force). The specification is made by Doglus Crockford on July 2006.
JSON files are saved with .json extension. Internet media type of JSON is "application/json".

What JSON looks like

We will now look how a typical JSON looks like. The following code snippet is a valid (you will see in a later chapter what is syntactically valid JSON) JSON representing information about a book.
  1. {  
  2.     "Title""The Cuckoo's Calling",  
  3.     "Author""Robert Galbraith",  
  4.     "Genre""classic crime novel",  
  5.     "Detail": {  
  6.         "Publisher""Little Brown",  
  7.         "Publication_Year": 2013,  
  8.         "ISBN-13": 9781408704004,  
  9.         "Language""English",  
  10.         "Pages": 494  
  11.     },  
  12.     "Price": [  
  13.         {  
  14.             "type""Hardcover",  
  15.             "price": 16.65  
  16.         },  
  17.         {  
  18.             "type""Kidle Edition",  
  19.             "price": 7.03  
  20.         }  
  21.     ]  
  22. }  
Now we will discuss what are basic constructs of JSON.

Basic Constructs

  • There four basic and built-in data types in JSON. They are strings, numbers, booleans (i.e true and false) and null. Besides there are two data types which are structured - objects and arrays.
  • Objects are wrapped within '{' and '}'. Arrays are enclosed by '[' and ']'. Objects are list of label-value pairs. Arrays are list of values.
  • Both objects and arrays can be nested.
  • strings, numbers, booleans (i.e true and false) and null can be used as values.
Following image and then text following will be useful to get you started with how JSON data is constructed.
A simple json file
So the entire content of the JSON data shown above is enclosed within an object. "Title": "The Cuckoo's Calling", "Author": "Robert Galbraith", "Genre": "classic crime novel", these are label-value pairs separated by commas. Labels and their values are separated by a colon (:). Notice that both labels and values are enclosed by quotations, since they are strings.
Notice the '"Detail"' label then. It contains another object, which again contains several label-value pairs. This is an example of how nesting (object within object in this case) is done in JSON.
Then '"Price"' label contains an array, which is turn contains two separate objects. Another example of nesting.
Also notice that numbers are not enclosed by quotations.

History of JSON

The name behind popularizing the JSON is Douglas Crockford. He used JSON is his company State Software around 2001.
In 2005, Yahoo started using JSON in it's web services.
In later 2006, Google started offering JSON in it's Gdata web protocol.
Today, JSON is one of the most widely used data-interchange format in web, and supported by most of the Web APIs (like twitter api) to fetch public data and creating applications out of them.

Comparison with Relational Database

Since JSON is used to host/represent data, we will discuss how it is different from the traditional Relational Database model used in RDBMS systems like MySQL, SQL Server etc. This may be useful for you to choose JSON over RDBMS or RDBMS over JSON depending upon the type and structure of data you want to deal with. Let's start with a comparison against certain features:
  • Structure : In relational database, it is tables, which are responsible for storing data in form of rows and columns. JSON uses objects and arrays - objects are label-value pairs and arrays are list of values. They can be nested recursively.
  • Metadata : In relational database, it is schema, which is used for storing data about the structure and type of the data to be stored and schemas are pre defined, i.e. they are created at the time of creation of database and tables, before you can store data. JSON also may use schema, to have a definition of the structure and type of data to represented, but it is not pre defined. Most of the time it is self describing, even if it uses a schema, it comes with much more flexibility than a schema used in relational database. But it would be judgmental to say that it is an advantage of JSON over Relational Database. Having an pre defined schema may have several benefits depending upon the data to be dealt with.
  • Retrieving data : Relational databases use Structured Query Language, a expressive and very powerful language, based on relational algebra to fetch data from database. JSON does not have any widely used or accepted language to query the data stored. JAQL and JSONiq are many of the query languages which mostly are work in progress to query data from JSON.
  • Sorting : SQL does the job in case of Relational Database. In case of JSON, since arrays often used, in programs, arrays can be sorted.
  • Application : There are many open source as well as commercial Relational Database systems are available - like MySQL, POstgreSQL, SQL Server, Oracle, DB2 etc. JSON is mostly applied with programming languages. But, there is also NoSQL systems. NoSQL systems use JSON format to store data. Some of the NoSQL systems use JSON format are - MongoDB, CoucheDB etc.
  • Learning curve: JSON is a clear winner here. Since the basic data types and structure used here are similar to those used in many programming languages, it is obvious that if you are coming from a programming background, you will pick things up in JSON pretty fast. RDBMS is a separate field of study on the other hand. But definitely, time you invest to learn Relational database return you several opportunities and benefits.
Now let's discuss a few use cases which will be useful.
Assume that you have to store information regarding students(name, id, class) and marks obtained by them in various subjects. Relational Database is suitable here than using JSON, since here we can have one table containing student detail and another table for marks obtained by them in various subjects.
Now assume that we have to represent information regarding students(name, id, class) and various projects they have completed in different subjects along with a brief description of the project. Assume that a student may complete any number of projects and any of number subjects they choose from. Notice that, in this case you may have any uniformity of the data to be stored. So, in this case JSON will be preferable than using Relational Database.

JSON vs XML

Since XML is also used as data interchange format widely, we will try to draw a comparison between them. The purpose of the comparison it's definitely not in the line of which is better, rather we will try to understand which one is suitable for storing specific kind of data.
  • XML is more expressive than JSON. XML sometimes also suffers from using tags repeatedly, where as JSON is much more concise.
  • XML is more complex than JSON.
  • There are several specifications to define schema(metadata) for XML, for example DTD and XSD. JSON schema is there for doing the same for JSON, but it is not as widely used as XML schemas.
  • XML can be used with most of the programming languages as JSON. But the point is, when you are working with XML, then you have you are actually trying match two systems those data structures are different. In case of JSON though, since objects and arrays are basic data structures used, it is easy to work with them in programs.
  • For selecting specific parts of an XML document, there is standard specification called XPath. This is widely used. In JSON, we have JSONPath to do the same, but not widely in use.
  • XML has Xquery specification for querying XML data. JSON though have JAQL, JSONiq etc, but they are not in use widely.
  • XML has XSLT specification which may be used to apply style to an XML document. JSON does not have any such thing.

Typical uses of JSON

API : API is the most widely used area where JSON is used for data exchange. Specially, web applications those have a social face, it has become obvious now that they have an API, so that developers can consume the huge amount of data collected by the app and then can create derivative apps. Twitter, Facebook, Linkedin, Flicker, Dribble, you name it, all the well known apps on internet today has an API and uses JSON as their preferred format for serving data to the developers. Out of these APIs, some have support for both JSON and XML, but some support only JSON.
We will see a simple demonstration of rottentomatoes API to get a feel of how JSON is used in APIs. In this demo, we are querying the rottentomatoes.com for name and thumbnail poster of the movie containing string "Life is beautiful" using JavaScript and Jquery. It returns the result in JSON format and then it is displayed on browser. You can have a live demo by clicking here. And following is a screenshot of it.
using JSON in API demo
NoSQL : This is another area where JSON is used. NoSQL databases like MongoDb, CouchDb uses JSON format to store data.
Since JSON structures can be transformed to JavaScript objects within the browser environment, it is very easy to work with. Moreover it can be integrated with server side JavaScript also. The following shows that in mongoDb, data is stored in JSON format (to be specific, a variant of JSON, called BSON is used). You can learn MongoDb in detail in our separate tutorial for MongoDb.
we select the database first. Our database name is w3r_demo here.
select database
Now we will insert some data to the collection (like table in RDBMS) books. The data we are entering is shown at the JSON data example above in this example.
insert data
We will select the data insert and display now.
select data
So this way we store data in JSON format in NoSQL database MongoDb.
AJAX : JSON is often used to retrieve data from server with AJAX. This is suitable because this way, retrieved data is presented to browser environment and then using JavaScript can be manipulated and rendered.
In the following demo we are using Jquery and AJAX to fetch the most recent 5 photographs of cats from Flicker. We can view a live demo here. And following is a screenshot.
JSON Ajax demo
Package Management : Since the complexity of web development has increased a lot, developers nowadays use tools to create a package of their application. That makes the app more easily deploy-able and later on it is also become easy to make modifications and integrate the changes. This way, the development and maintenance process becomes easier. There are number of package management tools are available, namely Bower, Yomen , NPM (Node Package Manager) etc. Most of these tools use a package.json file where the metadata (like name, version, description, file structure, dependencies, license information etc) are written.
Bellow is the package.json file from Twitter Bootstrap.
  1. {  
  2.     "name""bootstrap"  
  3.   , "description""Sleek, intuitive, and powerful front-end framework for faster and easier web development."  
  4.   , "version""2.3.2"  
  5.   , "keywords": ["bootstrap""css"]  
  6.   , "homepage""http://twitter.github.com/bootstrap/"  
  7.   , "author""Twitter Inc."  
  8.   , "scripts": { "test""make test" }  
  9.   , "repository": {  
  10.       "type""git"  
  11.     , "url""https://github.com/twitter/bootstrap.git"  
  12.   }  
  13.   , "licenses": [  
  14.     {  
  15.         "type""Apache-2.0"  
  16.       , "url""http://www.apache.org/licenses/LICENSE-2.0"  
  17.     }  
  18.   ]  
  19.   , "devDependencies": {  
  20.       "uglify-js""1.3.4"  
  21.     , "jshint""0.9.1"  
  22.     , "recess""1.1.8"  
  23.     , "connect""2.1.3"  
  24.     , "hogan.js""2.0.0"  
  25.   }  
  26. }  
So, you already might have an idea of how JSON is being used in real world and will be useful for you to learn JSON well, so that you can use it in your own projects.

What you will learn in JSON tutorials of w3resource

Here is a brief rundown of the tutorials you will come across in our series of JSON tutorials.
  • A detail discussion about data structures and values you can use in JSON.
  • Various tools you may use to view JSON online.
  • How to use JSONLint to validate JSON.
  • Some examples with explanations of JSON.
  • Working with PHP and JSON. We have discussed installation, how to various PHP functions to explore the power of JSON.
  • Working with JavaScript and JSON. JSON is a built in object in JavaScript. We have discussed how to convert JSON to string and string to JSON.
  • To select specific parts of a JSON data, you can use JSON Path. We have discussed how to use JavaScript and PHP to work with JSON Path.
  • If you are sending a query to fetch data residing on a domain different than domain from where the request is sent, you have to use JSONP to overcome a cross domain resource sharing bottleneck. We have discussed JSONP in a separate tutorial in this series.
  • We have also discussed BSON, a variant of JSON, used in MongoDb to store data.

Description

In this page you will learn about structures of JSON. you will also learn different forms of storing data in JSON.

Data Structures supported by JSON

JSON supports two widely used (amongst programming languages) data structures.
A collection of name/value pairs. Different programming languages support this data structure in different names. Like object, record, struct, dictionary, hash table, keyed list, or associative array.
An ordered list of values. In various programming languages, it is called as array, vector, list, or sequence.
Since data structure supported by JSON is also supported by most of the modern programming languages, it makes JSON a very useful data-interchange format.

Data Types in JSON

JSON supports an array of data types. We will discuss those in detail in the following section of this page of the JSON tutorial.

Object

Syntax

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

Explanation of Syntax

An object starts and ends with '{' and '}'. Between them, a number of string value pairs can reside. String and value is separated by a ':' and if there are more than one string value pairs, they are separated by ','.

Example

{
"firstName": "Bidhan",
"lastName": "Chatterjee",
"age": 40,
"email":"bidhan@example.com"
}
In JSON, objects can nest arrays (starts and ends with '[' and ']') within it. The following example shows that.
{
"Students": [

{ "Name":"Amit Goenka" ,

"Major":"Physics" },
{ "Name":"Smita Pallod" ,
"Major":"Chemistry" },
{ "Name":"Rajeev Sen" ,
"Major":"Mathematics" }
]
}

Array

Syntax

[ value, .......]

Explanation of Syntax

An Array starts and ends with '[' and ']'. Between them, a number of values can reside. If there are more than one values reside, they are separated by ','.

Example

[100, 200, 300, 400]
If the JSON data describes an array, and each element of that array is an object.
[
{
"name": "Bidhan Chatterjee",
"email": "bidhan@example.com"
},
{
"name": "Rameshwar Ghosh",
"email": "datasoftonline@example.com"
}
]
Remember that even arrays can also be nested within an object. The following shows that.
{
"firstName": "Bidhan",
"lastName": "Chatterjee",
"age": 40,
"address":
{
"streetAddress": "144 J B Hazra Road",
"city": "Burdwan",
"state": "Paschimbanga",
"postalCode": "713102"
},
"phoneNumber":
[
{
"type": "personal",
"number": "09832209761"
},
{
"type": "fax",
"number": "91-342-2567692"
}
]
}

Value

Syntax

String || Number || Object || Array || TRUE || FALSE || NULL
A value can be a string, a number, an object, an Array, a Boolean value (i.e. true or false) or Null. This structure can be nested.

String

A string is a sequence of zero or more Unicode characters, enclosed by double quotes, using backslash escapes. A character is represented as a single character string, similar to a C or Java string.
The following table shows supported string types.
String TypesDescription
"A double quotation mark.
\Reverse Solidus
/Solidus
bBackspace
fform feed
nnewline
rCarriage return
tHorizontal tab
uFour hexadecimal digits

Number

The following table shows supported number types.
Number TypesDescription
IntegerPositive or negative Digits.1-9. And 0.
FractionFractions like .8.
Exponente, e+, e-, E, E+, E-

Whitespace

Whitespace can be placed between any pair of supported data-types.
 - See more at: http://www.w3resource.com/JSON/structures.php#sthash.DidfQdNv.dpuf




Objective


While working with JSON, often you may need a JSON viewer. This document discusses several online JSON viewer. Hopefully, this will help you to select one depending upon your requirement.

jsonviewer.stack.hu


This may be the most widely used online JSON viewer. Indeed it is feature rich to be used widely.

jsonviewer.stack.hu

You can directly copy your JSON text in this online viewer. Or you may use the load JOSN data button to supply an url and the viewer will load JSON form that resource. After the JSON code is visible in the viewer, you can click on Format to format the code.

jsonviewer.stack.hu format

Clicking on Viewer then will change the mode of the viewer and you can expand or collapse the JSON tree on the left hand side pane to view the name and values on the right hand side pane.
jsonviewer.stack.hu view
In the Text mode, you can minify the JSON code by clicking on the Remove white space.
jsonviewer.stack.hu remove white space
And finally, you can clear the code by clicking on Clear.

jsoneditoronline.org

jsoneditoronline.org is another excellent JOSN viewer. It comes with a default JSON code which you may clear by clicking on clear button.You may load your own JSON code by clicking on Open and then you choose to open from a local file (Open file) and form a url (Open url).
josn online editor open
You click on JSON to editor and you can see the code you loaded as a JSON tree on the right hand side pane.
josn online editor JSON to Editor
You can then expand and collapse the tree to view various components of the JSON tree.
josn online editor tree
There is search box on the editor, which you may use to search various components of the JSON code.
josn online editor search
Once you click on the Save button, the document in question is saved on your local machine (within default download location).
On the left hand pane, the left most button is to format your JSON code.
josn online editor format
And the button net to that is to remove all the white spaces and make it compact.
josn online editor compact

Online JSON Tree Viewer Tool

This is tool is located at http://www.jquery4u.com/demos/online-json-tree-viewer/. You can either click on Choose a file and upload a JSOn file or you may click on Copy and Paste and simply copy JSON code from a source.
jquery4you json viewer
Once the code is there, click on the Generate JSON tree to obtain a tree view of the JSON code.
jquery4you json generate
You can now Collapse and Expand the JSON tree. Another good feature of this tool is, when you select a component of the JSON tree, you can see a popup on the browser showing you the path of the JSON object selected.
jquery4you json select
You can not save, clear or remove white space using this tool though.

JSON Visualization

This is feature rich online JSON viewer, available at http://chris.photobooks.com/json/default.htm. You can paste the JSON code under Input. You may also click Load and load a JSON file from remote.
json visualization
Click on render to generate either JSON or HTML, depending upon the selection you have made under radio boxes of Output.
json visualization render
By clicking on Expand/Collapse you can expand and collapse the JSON tree rendered. You can click on any of the JSON component and it shows it's location in the JSON tree.
json visualization selection
Clicking on validate will validate your JSON code.
Clicking on reencode will reencode the JSON code.
json visualization reencode

Json viewer

This tool is available at http://www.jsonviewer.com/. Like other tools, this also allows you to load JSON from either url or you can directly paste the code. Though the loading from url is available on IE only. After you click on Parse JSON data, Json Object view is rendered.
json viewer

JSON Parser Online

You can access this tool at http://json.parser.online.fr/. Once you paste code on the left hand side panel, you can view JSON tree w.r.t string parsing and eval.
JSON Parser online
Clicking on the Options opens a menu and you can choose various options from there.
JSON Parser online options
This tool has several JSON samples including one Invalid JSON sample which is great, particularly for beginners.
JSON Parser online samples

Free Online JSON Parser

http://jsonparser.com/ offers this tool. You can copy code, format, view JSON tree and collapse and expand the tree with this tool.
online json parser

JSONView in Chrome

This browser extension for Chrome is an excellent tool. You can obtain it from https://chrome.google.com/webstore/detail/jsonview/chklaanhfefbnpoihckbnefhakgolnmc?hl=en. You can use the context menu to copy the JSON path or the value.
JSON View
This has an extension for Firefox also. You can obtain it from here:https://addons.mozilla.org/EN-us/firefox/addon/jsonview/.
You have any other tool in mind? Let us know. And of course share it with your friends and colleagues.
- See more at: http://www.w3resource.com/JSON/online-JSON-viewer.php#sthash.ltCxDfDe.dpuf


What is JSONLint


JSONLint is an opensource project which allows you to validate your JSON data. Since when you are working with any programming language and JSON, if your JSON data is not properly formatted, it can cause error, it is better to validate your JSON data beforehand.

You can check your JSON data by simply copying it to the JSONLint online (http://jsonlint.com/).

JSONLint - the JSON validator

Example of validating JSON with JSONLint


We will take simple piece of code and with the help of JSONLint, we will validate that. Here is the code

{ "firstName": "Bidhan", "lastName": "Chatterjee", age: 40, "email":bidhan@example.com }
Upon copying this code in the JSONLint and pressing Validate button, it shows the following error :
JSONLint - showing validation error
So you can see that it shows you the line number and the kind of error occurred.
Here, it says that it says that 'age' must be written as a string on line number 3. So, we enclose age as "age" directly in the JSONLint and press validate button again.
Here is the output :
JSONLint - showing validation error 2
Now it says that the error is on line 5. It should be "bidhan@example.com" instead of bidhan@example.com. And after making that change it validates the JSON.
..
JSONLint - validatd JSON
- See more at: http://www.w3resource.com/JSON/validate-JSON-with-JSONLint.php#sthash.UlxWCzUP.dpuf








XML and JSON

JSON Document
{
"Dogs": [
{
"category": "Companion dogs",
"name": "Chihuahua"
},
{
"category": "Hounds",
"name": "Foxhound"
}
]
}
XML Document
<dogs>
<dog>
<category>companion dogs</category>
<breed>Chihuahua</breed>
</dog>
<dog>
<category>Hounds</category>
<breed>Foxhound</breed>
</dog>
</dogs>

MySQL and JSON

The following is a MySQL table. Using the PHP-MySQL code bellow the table, we have created a JSON document.
MySQL Table
DEMO MySQL TABLE
PHP MySQL code to extract data from MySQL table and display as JSON.
<?php
$host="localhost"; //replace with your hostname
$username="root"; //replace with your username
$password=""; //replace with your password
$db_name="demo"; //replace with your database
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select * from emp_info"; //replace emp_info with your table name
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_row($result)){
$json['emp_info'][]=$row;
}
}
mysql_close($db_name);
echo json_encode($json);
// please refer to our PHP JSON encode function tutorial for learning json_encode function in detail
?>
JSON Document
{"emp_info":[["Rameshwar Ghosh","rameshwar@example.com"],["Bidhan Chatterjee","bidhan@example.com"],["Rebati Banerjee","rebati@example.com"]]}

MongoDB and JSON

The following example shows how MongoDB stores data in JSON format. We have a table called 'userdetails' and if we run a query to select all the records of
the table, we get data in JSON format.
mongodb json format data

Tumblr API and JSON

tumblr.com is messaging platform. It offers an API to retrieve data. Here is a simple command to retrieve blog information. For the sake of simplicity, we have kept authentication method out of the scope of this document.
http://api.tumblr.com/v2/blog/web-development-and-seo.tumblr.com/info
Where "web-development-and-seo" is the blog name from where you want to retrieve data. When browser is pointed to this URL, we get following output, which is in JSON format.
{"meta":{"status":401,"msg":"Not Authorized"},"response":[]}.
 - See more at: http://www.w3resource.com/JSON/JSON-example.php#sthash.TWSBVf6w.dpuf







What is serialize and deserialize

Often you would find these two terms - serialize and deserialize. With the context of working with JavaScript and JSON, in a nutshell, to get JSON value from JavaScript value is serialization and when it's other way (JSON to JavaScript) is deserialization.

JavaScript JSON object

The JavaScript JSON object comprises methods using which you can convert JavaScript values to JSON format and JSON notation to JavaScript values.
We will now discuss two JSON methods - JSON.stringify and JSON.parse with examples.

JSON.stringify

JSON.stringify is used to convert JavaScript values to JSON.

JSON.stringify example

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JavaScript JSON.stringify example | JSON tutorial | w3resource</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body onload="w3resource();">
<h1>This is an example of JavaScript JSON.stringify</h1>
<script type="text/javascript">
function w3resource()
{
var w3r = {};
w3r.PHP = "w3resource PHP tutorial";
w3r.Examples = 500;
var w3r_JSON = JSON.stringify(w3r); // w3r_JSON holds {"PHP":"w3resource PHP tutorial","Examples":500}
alert (w3r_JSON);
}
</script>
</body>
</html>

JSON.parse

JSON.parse is used to convert JSON notation to JavaScript values.

JSON.parse example

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JavaScript JSON.parse example | JSON tutorial | w3resource</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body onload="w3resource();">
<h1>This is an example of JavaScript JSON.stringify</h1>
<script type="text/javascript">
function w3resource()
{
var w3r = {};
w3r.PHP = "w3resource PHP tutorial";
w3r.Examples = 500;
var w3r_JSON = JSON.stringify(w3r); // w3r_JSON holds {"PHP":"w3resource PHP tutorial","Examples":500}
alert(w3r_JSON);
var convertToJS = JSON.parse(w3r_JSON);
var StringAgain = JSON.stringify(w3r);
alert(StringAgain);
}
</script>
</body>
</html>

Why you should not use eval() with JSON

It's not safe to parse JSON using eval because eval allows much more syntax than JSON. Even it can be extended up execution of arbitrary code, which leaves a big security whole for your website.
 - See more at: http://www.w3resource.com/JSON/working-with-javascript.php#sthash.dnARTE3F.dpuf







What is JSONPath

JSONPath is a lightweight library to find and extract sections from a JSON data. It can be used with both JavaScript and PHP.

Obtain JSONPath

To work with JSONPath and JavaScript, you need to download jsonpath.js. You can download it from http://code.google.com/p/jsonpath/.
Once downloaded, you need to include the said js file in your webpage and you are ready to use it.

Syntax

jsonPath(obj, expr [, args])

Parameters

ParameterDescription
obj (object|array)This parameter represents the Object representing the JSON structure.
expr (string)This parameter represents JSONPath expression string.
args (object|undefined)This parameter represents Object controlling path evaluation and output. As of this writing only one member is supported.
args.resultType ("VALUE"|"PATH")By default, this parameter causes the result to be matching values. Else normalized path expressions.

Return Values

Return valueDescription
arrayAn array comprising either values or normalized path expressions which match the path expression supplied as input.
falseThis is returned if no match is found.

Example of using JSONPath with JavaScript

The JSON we will be working with is as follows :
{ "MovieDatabase": {
"movie": [ 
{ "name":"The Change-Up",
"genre": "comedy",
"director": "David Dobkin",
"Facebook_like": 252
},
{ "name":"Rise of the Planet of the Apes",
"genre": "SciFi",
"director": "Rupert Wyatt",
"Facebook_like": 472
},
{ "name":"30 Minutes or Less",
"genre": "adventure",
"director": "Ruben Fleischer",
"Facebook_like": 114
},
{ "name":"Final Destination 5",
"genre": "Horror",
"director": "Steven Quale",
"Facebook_like": 241
}
]
}
}
JavaScript Code to find and extract various parts of the above JSON data is as follows (note that since we will be using a method from json.js parser, you need to download and include that too ) :
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JavaScript JSONPath example | JSON tutorial | w3resource</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="/JSON/json.js"></script>
<script type="text/javascript" src="/JSON/jsonpath.js"></script>
</head>
<body>
<h1>This is an example of JavaScript with JSONPath</h1>
<script type="text/javascript">
var json = { "MovieDatabase": {
"movie": [ 
{ "name":"The Change-Up",
"genre": "comedy",
"director": "David Dobkin",
"Facebook_like": 252
},
{ "name":"Rise of the Planet of the Apes",
"genre": "SciFi",
"director": "Rupert Wyatt",
"Facebook_like": 472
},
{ "name":"30 Minutes or Less",
"genre": "adventure",
"director": "Ruben Fleischer",
"Facebook_like": 114
},
{ "name":"Final Destination 5",
"genre": "Horror",
"director": "Steven Quale",
"Facebook_like": 241
}
]
}
};
result = "";
result += jsonPath(json, "$.MovieDatabase.movie[*].director").toJSONString() + "<br />";
//find all directors result += jsonPath(json, "$..director").toJSONString() + "<br />";
//find all directors result += jsonPath(json, "$.MovieDatabase.*").toJSONString() + "<br />";
//find all movies result += jsonPath(json, "$.MovieDatabase..Facebook_like").toJSONString() + "<br />";
//find all facebook lies of all the movies result += jsonPath(json, "$..movie[(@.length-1)]").toJSONString() + "<br />";
//the last movie in data result += jsonPath(json, "$..movie[-1:]").toJSONString() + "<br />";
//the last movie in data result += jsonPath(json, "$..movie[0,1]").toJSONString() + "<br />";
//first two movies result += jsonPath(json, "$..movie[:3]").toJSONString() + "<br />";
//first three movies result += jsonPath(json, "$..movie[?(@.genre)]").toJSONString() + "<br />";
//all movies with genre result += jsonPath(json, "$..movie[?(@.Facebook_like>200)]").toJSONString() + "<br />";
//movies with facebook like more that 200 result += jsonPath(json, "$..*").toJSONString() + "\n";
// all members in the JSON document document.write(result);
</script>
</body>
</html>
 - See more at: http://www.w3resource.com/JSON/JSONPath-with-JavaScript.php#sthash.KwXOC1h2.dpuf

1 comments:

Try this online tool Json Viewer @ http://codebeautify.org/jsonviewer