Skip to main content

JSON : Tutorial and Usage


Json Introduction


What is JSON?

  • JSON stands for JavaScript Object Notation
  • JSON is lightweight text-data interchange format
  • JSON is language independent *
  • JSON is "self-describing" and easy to understand
JSON uses JavaScript syntax for describing data objects, but JSON is still language and platform independent. JSON parsers and JSON libraries exists for many different programming languages.
Json Format Example :
{
    "employees": [
        {
            "firstName": "John",
            "lastName": "Doe"
        },
        {
            "firstName": "Anna",
            "lastName": "Smith"
        }
    ]
}

Why JSON?
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
  • eval() the JSON string

JSON Values
JSON values can be:
  • A number (integer or floating point)
  • A string (in double quotes)
  • A Boolean (true or false)
  • An array (in square brackets)
  • An object (in curly brackets)
  • null
More JSON Introduction 
Json Validator
JSON Lint is a web based validator and reformatter for JSON, a lightweight data-interchange format.

Json Usage 

PHP

Returns the JSON representation of a value
Decodes a JSON string

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

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


PERL

Library Require : $tar xvfz JSON-2.53.tar.gz
 
encode_json()
converts the given Perl data structure to a UTF-8 encoded, binary string
decode_json()
used for decoding JSON in Per



Example
#!/usr/bin/perl
use JSON;
use Data::Dumper;

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

$text = decode_json($json);
print  Dumper($text);


Output

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


JAVA

Library Required : JSON.simple 

Encoding in JAVA

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);
   }
}

While compile and executing above program, this will produce following result:
{"balance": 1000.21, "num":100, "is_vip":true, "name":"foo"} 

Decoding Json in JAVA 

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);
      }
   }
}
While compile and executing above program, this will produce following result:
The 2nd element of array
{"1":{"2":{"3":{"4":[5,{"6":7}]}}}}

Field "1"
{"2":{"3":{"4":[5,{"6":7}]}}}
{}
[5]
[5,2]



JAVASCRIPT

No library required  
 
Example
var jsonObj = JSON.parse(json_string);
var name =  jsonObj.name;
var country = jsonObj.country;



You can also check our Microservices post

Introduction to Microservices

Comments

Popular posts from this blog

Login with Google Account using PHP / Javascript using OAuth2.0

Login with Google Account using PHP with code This post have Complete Code for Login / Sign-in  with google Account  using PHP / Javascript with oAuth2.0 Basically today we have seen almost every website needs you to register yourself before you can post or take part in any discussions to the website. But it become a tedious task to register and login to many different sites. Solution is to provide the users the option to Login with existing Google / Facebook account as almost everyone have Facebook and Google account.. In this post, I am going to explain how to integrate the Google Login / Sign in  for your website. For this,  First you need to create your Client ID, Client Secret and your developer API key. For this go to https://developers.google.com/identity/sign-in/web/sign-in Click on the button Create Project. A new window will open up. Please select Create Project / or select already created Project. It will then ask for about type ...

How To Set Up Apache Virtual Hosts on Ubuntu

How to setup Virtual Host in Ubuntu 16 / Ubuntu 18 on localhost / local machine To run the website with host on localhost(With LAMP) becomes important in many cases. This blog post will demonstrate how to achieve this. Assuming you have LAMP already installed and reading the code from (/var/www/html) Follow the simple steps below Create the code base To Create the code, simply create a directory named localweb inside /var/www/html. Create a file index.php inside localweb directory Content of index.php file <?php  echo "Local Website"; ?> Now our code base is set, so we need to configure apache Go to apache directory cd  /etc/apache2/sites-available/ Create one file named localweb.conf with content <Directory /var/www/html/localweb/>     AllowOverride All </Directory> <VirtualHost *:80>     ServerAdmin admin@localweb.com     ServerName localweb.com   ...

ORCAM - Blind can read too.!!

ORCAM: The technology that was developed mainly with the aim – to help to help the visually impaired and blind regain the functionalities that were lost. Yeah. So now even visually impaired guys can get to know even the smallest written things just by pointing towards them, like the reading the book. Yes. Even those who are completely blind, can even read a book using ORCAM. SO what actually is ORCAM.????? A visual system with human like performance to help visually impaired people Here is a look towards ORCAM-See for yourself Search Results It is a simple device with a camera and earphone   that fits in the simple glasses   and uses the Text-to-speech technology to read the objects and sends the user in the voice format with the help of the earphone. The   OrCam device is able to identify thousands of objects, including the faces of loved ones, dogs, buses, newspaper text and store signs, all with the point o...