Json Examples

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 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 will be 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]

 

 

Json Examples

  Json with Ruby

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/ruby

require '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"]

}

 

Json Examples

JSON with Python:

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

Function Libraries
encode Encodes the Python object into a JSON string representation.
decode Decodes a JSON-endoded 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/python

import demjson

 data = [ { '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/python

import demjson

 json = '{"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}

 

Json Examples

JSON with Perl:

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

Function Libraries
encode_json Converts the given Perl data structure to a UTF-8 encoded, binary string.
decode_json Decodes a JSON string.
to_json Converts the given Perl data structure to a json string.
from_json Expects a json string and tries to parse it, returning the resulting reference.
convert_blessed Use 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/perl

-          use 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/perl 

package 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_text

 or 

$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/perl

use 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

};

 

Json Examples

Json with PHP:

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:

Function Libraries
json_encode Returns the JSON representation of a value.
json_decode Decodes a JSON string.
json_last_error Returns 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)
      
      }