Site icon Software Test Tips

JSON – Quick Guide For Beginners

JSON Quick Guide For Beginners

JSON is a library based on the JavaScript scripting language, which is used to serialize JSON to Java objects and vice versa. You can use the JSON library freely, as it is open-source. This article is a quick guide about JSON. You will learn everything about JSON in this post. 

Table of Contents

What is JSON?

JSON implies Java-Script Object Notation. JSON is a text format, which uses human-readable and understandable data for transmitting and storing several data objects, like arrays, attribute-value pairs, etc. The JSON library holds serializable values in it. The JSON text form is language-independent. JSON is extended from the JavaScript programming language. 

In the early 2000s, Douglas Crockford specified the JSON data format. JSON’s official website was released in 2002, www.json.org. Later, JSON became exceptionally popular. In 2005, JSON included the web services offered by Yahoo!. JSON started becoming popular worldwide. In 2013, it existed as an ECMA International Standard. The latest JSON version was launched in 2017. ECMAScript is the superset of the JSON. 

JSON is used for stateless systems and the communication protocol of the server to the browser without requiring any plugins, like Java applets or Flash. This Java-based library has internet media type or MIME type as application/json, whereas the JSON’s file extension is .json. JSON’s uniform type identifier is public.json. As JSON is extended from the JavaScript scripting language, it is usually used with JavaScript. The code is available in several programming languages for parsing and generating JSON data.

JSON Syntax and Example

Here, we shall see how the syntax of JSON is. The JSON syntax is the subset of the JavaScript syntax, as JSON is extended from JavaScript. JSON’s syntax involves:

JSON Syntax:

{ name : [ value1, value2, ...]}

JSON Example:

{
"Employee" : [
{
"emp_id" : "A01",
"emp_name" : "John",
"emp_position" : "Manager"
},
{
"emp_id" : "A03",
"emp_name" : "Oliver",
"emp_position" : "HR"
}
]
}

We have stored Employee information using JSON. Employee information consists of the employee’s name, ID, and position. However, there are two data structures supported by JSON. They are as follows:

1. An ordered list of values:

An ordered list of values involves array, vector, list, sequence, etc. All these data structures hold values in a sequential manner. 

2. Collection of name-value pair:

Another JSON data structure involves a name-value pair. Each element is represented with a name and its respective value. 

Features of JSON

JSON is a text format that holds data in a well-structured and easy-to-access format. Here are some most desirable JSON features that you should know.

1. Easy to use:

One of the significant characteristics of JSON is it is exceptionally straightforward and easy to use. JSON’s application program interface provides a high-level GUI, making general use-cases more simplified for users. 

2. Performance:

Another primary feature of JSON is its performance. It requires significantly less memory space and is exceptionally quicker and faster. Therefore, JSON is best suited for large object systems. 

3. Language Independent:

Though JSON is derived from the JavaScript scripting language, it is independent of programming languages. It works with multiple programming languages. For instance, if you desire to change the server-side programming language completely, you can use JSON, as it has a similar programming structure for multiple languages. 

4. Standard Structure:

JSON has a standard structure. All JSON objects are written in a standard format, making it easier for programmers to use JSON objects in their code.  

5. Open-source:

JSON is an open-source google library based on JavaScript scripting language. When you use JSON objects in your code, that code’s result is clean and comfortable to read. There is no need for other libraries for JSON processing. 

When to use JSON?

There are several situations where you can use JSON. These situations are listed below:

JSON Data Types

JSON library has six primary data types. They are String, Number, Null, Boolean, Array, and Object. Let us see each JSON data type in detail with examples. 

1. String:

String in JSON implies a sequential collection of zero or multiple Unicode characters. Each Unicode character is placed in double-quotes. For escaping the String in JSON, make use of a backslash (\). Several string types are present in JSON. They are listed below with their descriptions. 

JSON String TypeDescription
BYou can use B for adding backspace. 
UU implies four hexadecimal digits. 
NYou can use the N String type for creating a new line. 
You can add a front slash (/) for solidus.
** is used for double-quotes. 
\\ is the opposite of /. It is used for reverse solidus. 
RYou can use the R String type for carriage return.
FF implies Form Feed.
TT is used for displaying the horizontal tab. 

JSON String Syntax:

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

JSON String Example:

var obj = { city : 'Chicago'}

2. Number:

Another JSON data type is Number. It may include either a fractional part, exponent, or simply signed integers. Remember that the Number JSON data type does not have NaN, hexadecimal, and octal formats. The Number consists of floating point integers with double precision. Below are the three formats supported by JSON Number data type:

Number Data TypeDescription
IntegerIntegers include positive and negative numbers ranging from 1-9. It also involves 0. 
FractionThe Number data type also contains fractions, like 3. 
ExponentYou can use exponents, e e+, in Number data type.

JSON Number Syntax:

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

JSON Number Example:

var obj = {age : 45}

3. Array:

We are very well acquainted with arrays. An array is a collection of values. It stores all values in order. In JSON, array elements are enclosed in square brackets. Each array element is separated by a comma (‘,’). When the key values are of sequential integers, you must use the JSON array. Let us see the JSON array syntax and example. 

JSON Array Syntax:

[value, .....]

JSON Array Example:

{
"info": [
{
"name" : "John",
"age" : "19"
},
{
"name" : "Oliver",
"age" : "22"
},
{
"name" : "Steve",
"age" : "20"
}
]
}

4. Boolean:

JSON Boolean data type has two output values, True and False. Below are the JSON Boolean data type’s syntax and example.

JSON Boolean Syntax:

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

JSON Boolean Example:

var obj = { stud_name : 'John', sub_marks : 30, distinction : false}

5. Object:

Another JSON data type is an object. An Object data type is the opposite of the array data type. Unlike an array, an object holds values in an unordered manner. All object elements and values are embedded in curly brackets ({ }). Each element in the object data type is separated using a comma (‘,’). All keys in the object data type should be of different types. 

JSON Object Syntax:

{ string : value, ....}

JSON Object Example:

{
"stud_id" : "A1098",
"name" : "Steve",
"jobrole" : "Manager"
}

6. Null:

Null implies empty. 

JSON Null Syntax:

null

JSON Null Example:

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

7. Whitespace:

Whitespace is another JSON data type, which can be inserted between any two name-value pairs or tokens. The primary application of Whitespace is to make the JSON code more human-readable. Below are the syntax and example of using whitespace in the JSON code. 

JSON Whitespace Syntax:

{ string: “ “,...}

How to create JSON Objects?

Creating JSON objects is a very simple and straightforward method. You can use the JavaScript scripting language for creating JSON objects. JSON objects can be created using multiple ways. Let us know the various forms of making JSON objects.

How to create an empty JSON object?

Use the below syntax to create an empty JSON object. 

var obj = { };

Here, ‘obj’ is an empty JSON object. 

How to create a new JSON object?

Use the below JSON syntax to create a new object. 

var obj = new Object();

A new JSON object, ‘obj,’ gets created. 

How to create a JSON object with name and value?

For creating a JSON object with name and value, we shall take one example. Take the name attribute as ‘employee’ and represent its value in String data type. Let another name attribute be ‘age’ and represent its value in the Number data type. 

var obj = { "employee" : "Steve", "age" : 45);

Difference between JSON and XML

In this segment of the post, we shall look at the primary differences between JSON and XML. The below table depicts the fundamental difference between JSON and XML. 

JSONXML
JSON implies JavaScript Object Notation. XML implies Extensible Markup Language. 
JSON includes several data types, like String, Boolean, Number, Array, and Null. XML only includes the String data type. Hence, all XML data is represented in String. 
The entire JSON data is easily understandable by humans. XML data is not easily understandable by humans. 
JSON is not a markup language. Hence, it cannot display data. XML is a markup language and possesses data displaying capabilities. 
JSON does not allow namespaces. XML allows namespaces. 
JSON does not have end tags. XML has both start and end tags. 
JSON does not permit you to write comments in code. XML permits you to add comments in the XML code. 
UTF-8 encoding is the only encoding type supported by JSON. Several encoding techniques are supported by XML. 

The above table might have cleared all your doubts regarding JSON and XML. Let us now see how JSON and XML differ from each other using examples. 

JSON Example

{
"stud" : [
{
"stud_id" : "S01",
"stud_name" : "Sam",
"stud_age" : 13
},
{
"stud_id" : "S03",
"stud_name" : "Sandy",
"stud_age" : 15
}
]
}

XML Example

<?xml version="1.0" encoding="UTF-8" ?>
<root>
<stud>
<stud_id>S01</stud_id>
<stud_name>Sam</stud_name>
<stud_age>13</stud_age>
</stud>
<stud>
<stud_id>S03</stud_id>
<stud_name>Sandy</stud_name>
<stud_age>15</stud_age>
</stud>
</root>

What is JSON.simple?

We have seen precisely what JSON is. It is a data format, which keeps data in a human-readable form and can be used in many programming languages. If you wish to transfer JSON objects into Java, what would you do? Here is a library for sharing JSON objects or data to the Java code. This library is called JSON.simple

JSON.simple is a toolkit that enables JSON data to read and write in Java. In other terms, JSON.simple is a library that allows you to encode and decode JSON objects in Java. There is a special package called org.json.simple, which holds five different JSON API classes. These five JSON API classes are as follows:

  1. JSONValue
  2. JSONString
  3. JSONObject
  4. JSONNumber
  5. JSONArray

Environmental Set-up for JSON.simple

You know what JSON.simple is and what its use. How to use JSON.simple? We understand that the JSON.simple toolkit is used for encoding and decoding JSON data to Java language. Therefore, the first requirement for setting up the JSON.simple environment is to have the Java Development Kit (JDK) installed on your computer system. 

For installing JDK on your system, remember to install the JDK of version 1.5 and above. There are no other extra JDK installation requirements, like system memory, operating system, or disk space. 

Step 1: Checking Java Installation on the system:

Many users may have Java installed on their systems. In such cases, you just need to check whether your system has Java installed on it or not. Checking for Java installation is a very straightforward process. You need to use only one command on the command prompt. Remember that this command varies according to the operating system type. FOr Windows, macOS, and Linux, this command changes. 

Let us see the command for verifying Java installation on Windows, Linux, and macOS systems.

1. Microsoft Windows:

In the Windows system, open the command prompt and type,

c:\>java -version

When you type this command and click enter, it will generate your system’s Java version as the output. The output is displayed as follows:

Java version "1.8.0_101"
Java(TM) SE Runtime Environment (build 1.8.0_101)

Here the version of your JDK appears. 

2. Linux:

For the Linux system, you need to open your command terminal and type,

$ java -version

The output for Linux systems is the same as that of the Windows systems. The above command will result in

Java version "1.8.0_101"
Java(TM) SE Runtime Environment (build 1.8.0_101)

3. Mac OS X:

Consider that your system name is john. For the Mac OS X, open your system’s terminal and write

machine:< john$ java -version

Like the Windows and Linux systems, Mac OS X will generate the same output for the above command. 

Java version "1.8.0_101"
Java(TM) SE Runtime Environment (build 1.8.0_101)

This was all about verifying the Java installation on our systems. What if you do not have Java installed? You have to install Java and set up your system’s environment variable’s path to JDK in such situations. We will see the entire Java installation process in Step 2. 

Step 2: Installing Java and Setting Java Environment 

If your computer system does not have Java, you have to download JavaSE from this website

You must ensure that you download the JavaSE compatible with your system. We will guide you in setting up the Java environment with version “1.8.0_101”. After downloading JavaSE, run the .exe file and install it. 

Once you install, you have to set-up the Java environment. Follow the below steps to set-up the Java environment. 

Consider that you have installed JDK on C:\Program Files\Java\jdk.

Export JAVA_HOME = /Library/Java/Home

Go to My Computer and right-click on it. Click on Properties, and go to ‘Advanced Tab’. Later, click on environment variables. Choose the ‘Path’ and append

C:\Program Files\Java\jdk-18.0.1_101\bin. 

export PATH = $PATH:$JAVA_HOME/bin/ 

Step 3: Download JSON.simple

Now, you know how to download Java and set up the environment variable. After downloading, you can also check your Java version using the ‘java -version’ command. The next step is to download the JSON.simple jar file. You can download the JSON.simple jar file from this website,

You must ensure that you download the JSON.simple jar file of the latest version. Download the json-simple-1.1.1.jar file and copy it into the folder, C:\>JSON. For all the three systems, Windows, Linux, and macOS, the jar file name is json-simple-1.1.1.jar. 

Step 4: Set-up the environment for JAVA_JSON

After downloading the JSON.simple jar file, you have to set-up the JAVA_JSON environment. Consider that the JSON folder on your system stores the json-simple-1.1.1.jar file. You have to fix the environment variable of JSON_JAVA to the place where you keep the JSON.simple jar file. In this situation, you have to place the JSON_JAVA environment variable to the JSON folder. 

We shall see how to set the JSON_JAVA environment variable for Windows, Linux, and macOS systems. 

export JSON_JAVA = /Library/JSON
export JSON_JAVA = /usr/local/JSON

Step 5: Setting CLASSPATH Variable

The last step for setting the JSON.simple environment is setting the CLASSPATH variable. The CLASSPATH environment variable is changed to the location of your JSON.simple jar file on the system. The following points will aid you in selecting the CLASSPATH environment variable for Windows, Mac OS X, and Linux systems. 

export CLASSPATH = $CLASSPATH:$JSON_JAVA/json-simple-1.1.1.jar:.
export CLASSPATH = $CLASSPATH:$JSON_JAVA/json-simple-1.1.1.jar:.

Your JSON.simple environment set-up is completed. 

Features of JSON.simple

The following shows JSON.simple features.

JSON.simple Java Mapping and Escaping Special Characters

Here, we will discuss the mapping between JSON.simple and Java. When you need to decode or parse, JSON.simple performs the mapping from left to right. Conversely, while encoding, it serves the mapping from right to left. The below table will show JSONsimple and Java Mapping. 

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

When you decode, org.json.simple.JSONArray is the default concrete class for java.util.List. For java.util.Map, the concrete class is org.json.simple.JSONObject. 

Now, we shall discuss JSON.simple’s escaping characters. There are seven special escaping characters, which cannot be used in JSON. All the below seven escaping characters are reserved. 

For escaping all the above-reserved characters in JSON.simple, you can use JSONObject.escape() method. Let us look at an example using JSONObject.escape() method. 

Example:

import org.json.simple.JSONObject;
public class JsonEscChar {
  public static void main(String[] args) {
      JSONObject jobj = new JSONObject();
      String str = "Welcome to JSON - Quick Guide /\"\.\b\f\t\r\n*";
      System.out.println(str);
      System.out.println("Result after using the escaping method.");
      str = jsonObject.escape(str);
      System.out.println(str);
  }
}

Output:

Welcome to JSON - Quick Guide /".
*
Result after using the escaping method.
Welcome to JSON - Quick Guide /\"\.\b\f\t\r\n*

In the output, we can see that before applying the JSONObject.escape() method, all special characters functioned correctly. ‘*’ appeared in the new line. After using the JSONObject.escape() method, special characters did not function. 

Encoding and Decoding JSON in Java

In this segment, we shall see encoding and decoding the JSON object in Java with examples. JSON.simple library is used for encoding and decoding the JSON object in Java. We have seen JSON.simple and Java mapping with a table. JSON.simple decodes the JSON object from left to right and encodes it from right to left. 

Encoding JSON in Java

For encoding the JSON object in Java, we will use JSONObject in our example. JSONObject is present in the java.util.HashMap package. If you are using JSONObject for encoding, element ordering is not necessary. For element ordering, you can go with JSONValue.toJSONString. The below example of JSON.simple encoding uses JSONObject. 

Example:

import org.json.simple.JSONObject;   
public class EncodeExample
{   
public static void main(String args[])
{   
JSONObject jsobj=new JSONObject();   
jsobj.put("id","RS02");   
jsobj.put("name", "John");   
jsobj.put("age", new Integer(45));
jsobj.put("position", "Manager");   
jsobjs.put("is_manager", new Boolean(true));
System.out.print(jsobj);   
}
}    

Output:

{"position": "Manager, "age": 45, "name": "John", "is_manager": true, "id": "RS02"}

We can observe that the output did not occur in an ordered manner, as we have used JSONObject. 

Let us now observe another example of encoding JSON object in Java using the Map function. In the Map() function, the output occurs in an ordered form. Map() function uses JSONValue.toJSONString. Let us take the same above example, but we will use the Map() function. 

Example:

import java.util.HashMap; 
import java.util.Map; 
import org.json.simple.JSONValue; 
public class EncodeExample1
{   
public static void main(String args[])
{   
Map mobj = new HashMap(); 
mobj.put("id","RS02");  
mobj.put("name","John");   
mobj.put("age",new Integer(45));   
mobj.put("position", "Manager");  
mobj.put("is_manager", new Boolean(true));
String jsonEmployee = JSONValue.toJSONString(mobj); 
System.out.print(jsonEmployee); 
}
}   

Output:

{"id": "RS02", "name": "John", "age": 45, "position": "Manager", "is_manager": true}

We can observe that all elements appeared in order in the above output, as we used JSONValue.toJSONString. Now, we shall see JSON Array encoding in Java. 

JSON Array Encoding in Java

In JSON Array encoding, all elements appear in one single array. Let us take the same above example for observing JSON array encoding in Java. 

Example:

import org.json.simple.JSONArray; 
public class ArrEncodeExample
{   
public static void main(String args[])
{   
  JSONArray jsarr = new JSONArray(); 
  jsarr.add("RS02");
  jsarr.add("John");   
  jsarr.add(new Integer(45));   
  jsarr.add("Manager");  
  jsarr.add(new Boolen(true));
  System.out.print(jsarr); 
}
}   

Output:

[ "RS02", "John", 45, "Manager", true]

All JSON elements are represented in an array in the above example. The above example involved a simple JSON array encoding in Java. 

JSON Array Encoding in Java using List

We can also encode the JSON array using the List data structure. It is possible using the ArrayList() function. We take the same data from the above example for encoding the JSON array using a list. 

Example:

import java.util.ArrayList; 
import java.util.List; 
import org.json.simple.JSONValue; 
public class ArrEncodeExample1
{   
public static void main(String args[])
{   
List lisarr = new ArrayList(); 
lisarr.add("RS02");
lisarr.add("John");   
lisarr.add(new Integer(45));   
lisarr.add("Manager");
lisarr.add(new Boolean(true));  
String jsonLisEmployee = JSONValue.toJSONString(lisarr); 
System.out.print(jsonLisEmployee); 
}
}    

Output:

[ "RS01", "John", 45, "Manager", true]

Decoding JSON in Java

While decoding the JSON object in Java, JSON.simple performs the mapping from left to right. Here is an example of JSON object decoding in Java. 

Example:

import org.json.simple.JSONObject; 
import org.json.simple.JSONValue; 
public class DecodeExample
{ 
public static void main(String[] args)
{ 
String str="{\"id\":\"RS02\",\"name\":\"John\",\"position\":\"Manager\",\"age\":45}"; 
Object dobj=JSONValue.parse(str); 
JSONObject jsobj= (JSONObject) dobj; 
String id = (String) jsobj.get("id");
String name = (String) jsobj.get("name"); 
String position = (String) jsobj.get("position"); 
long age = (Long) jsobj.get("age"); 
System.out.println(name+" "+salary+" "+position+" "+age); 
} 
}  

Output:

RS02 John Manager 45

Merging two Arrays in JSON.simple

In JSON.simple, we can combine two different arrays in one single array. Consider the two arrays. After merging two arrays, the resulting array will contain all elements of the first and second array. For merging two arrays, we use JSONArray.addAll() method in JSON.simple. 

Example:

import java.io.IOException;
import org.json.simple.JSONArray;
class ArrMergeExample
{
public static void main(String[] args) throws IOException
{
JSONArray l1 = new JSONArray();
l1.add("RS02");
l1.add("John");
l1.add(new Integer(45));
JSONArray l2 = new JSONArray();      
l2.add("Manager");
l2.add(new Boolean(true));
l2.add(null);
l2.add("California");
l1.addAll(l2);      
System.out.println(l1);      
}
}

Output:

[ "RS02", "John", 45, "Manager", true, null, "California"]

The resulting array contains elements from l1 and l2. 

Merging two objects in JSON.simple

We have seen merging two different arrays in one. Similarly, we can connect two other objects into one. We will use JSONObject.putAll() method to combine two objects into one. 

Example:

import java.io.IOException;
import org.json.simple.JSONObject;
class ObjMergeExample
{
  public static void main(String[] args) throws IOException
{
      JSONObject ob1 = new JSONObject();    
      ob1.put("id", "RS02"); 
      ob1.put("name", "John");
      ob1.put("age", new Integer(45));
      JSONObject ob2 = new JSONObject();      
      ob2.put("position", "Manager");
      ob2.put("is_manager", new Boolean(true));      
      ob1.putAll(ob2);      
      System.out.println(ob1);
  }
}

Output:

{"position": "Manager", "is_manager": true, "id": "RS02", "name": "John", "age": 45}

Primitive, Object, and Array in JSON.simple

In the above example, we have only used JSONArray. Here, we shall see how to use the JSONArray object. When you use the JSONArray object, your result will contain objects, arrays, and primitives. Below is an example of primitive, object, and array in JSONsimple. 

Example:

import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
class POAExample
{
public static void main(String[] args) throws IOException
{
JSONArray l1 = new JSONArray();
l1.add("RS02");
l1.add("John");
l1.add(new Integer(45));
JSONArray l2 = new JSONArray();      
l2.add("Manager");
l2.add(new Boolean(true));
l2.add(null);
l2.add("California");
JSONObject jsobj = new JSONObject();
jsobj.put("id", "RS02");
jsobj.put("name", "John");
jsobj.put("age", new Integer(45));
jsobj.put("position", "Manager");
jsobj.put("is_manager", new Boolean(true));
jsobj.put("list1", l1);
jsobj.put("list2", l2);
System.out.println(jsobj);      
}
}

Output:

{"list1": ["RS02", "John", 45], "position": "Manager", "age": 45", "is_manager": true, "id": "RS02", "list2": ["Manager", true, null], "name": "John"}

Therefore, the above result includes primitives, arrays, and objects. 

Combination of Primitive, Map, List in JSON.simple

Here is another example for you to understand how the JSON.simple supports the combination of primitives, lists, and the map. We will use the JSONValue object for combining the map, primitives, and list together. 

Example:

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.json.simple.JSONValue;
class  PMLExample
{
public static void main(String[] args) throws IOException
{
      Map ma = new LinkedHashMap();
      ma.put("RS01","Steve");
      ma.put("RS02","John");
      ma.put("RS03", "Oliver");
      ma.put("RS04": "Sam");
      List lst = new LinkedList();
      lst.add(ma);
      lst.add(new Boolean(true));
      lst.add(new Integer(3456));
      lst.add("Manager”);
      String jstr = JSONValue.toJSONString(lst);
      System.out.println(jstr);
  }
}

Output:

[ {"RS01": "Steve", "RS02": "John", "RS03": "Oliver", "RS04": "Sam"}, true, 3456, "Manager" ]

Combination of Primitive, List, Object, and Map in JSON.simple

In the above two examples mentioned, we have seen the combination of primitives, array, object and primitives, list, map. Here, we shall see the variety of all these data structures in one. We will use JSONObject and JSONValue in the below example. 

Example:

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
class AllCombExample {
public static void main(String[] args) throws IOException {
      JSONObject jsobj = new JSONObject();
      Map ma = new LinkedHashMap();
      ma.put("RS01","Steve");
      ma.put("RS02,"John");
      ma.put("RS03", "Oliver");
      ma.put("RS04", "Sam");
      List lst = new LinkedList();     
      lst.add("Manager");
      lst.add(new Boolean(true));
      lst.add("Infosys");
      jsobj.put("mapping", ma);
      jsobj.put("list", lst);
      String jsStr = JSONValue.toJSONString(jsobj);
      System.out.println(jsStr);
  }
}

Output:

{"mapping": {"RS01": "Steve", "RS02": "John", "RS03": "Oliver", "RS04": "Sam"}, "list": ["Manager", true, "Infosys"]}

Customized Output in JSON.simple

JSON.simple allows users to get a customized output using the JSONAware interface. To get a precise idea about customized output, we shall see one example of Employees, having an employee name and employee ID. 

Example:

import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONAware;
import org.json.simple.JSONObject;
class JsonDemo
{
  public static void main(String[] args) throws IOException
{
      JSONArray emp = new JSONArray();
      emp.add(new Employee("RS02","John", "HR"));
      emp.add(new Employee("RS04","Juliet", "Manager"));
      emp.add (new Employee("RS03", "Robert", "Manager"));
      System.out.println(emp);    
  }
}
class Employee implements JSONAware {
  String name;
  String id;
  String position;
  Employee(String name, String id, String position)
{
      this.name = name;
      this.id = id;
      this.position = position;
  }
  @Override
  public String toJSONString() {
      StringBuilder strb = new StringBuilder();
      strb.append("{");
      strb.append("id");
      strb.append(":");
      strb.append("\"" + JSONObject.escape(id) + "\"");
      strb.append(",");
      strb.append("name");
      strb.append(":");
      strb.append("\"" + JSONObject.escape(name) + "\"");
      strb.append(",");
      strb.append("position");
      strb.append(":");
      strb.append("\"" + JSONObject.escape(position) + "\"");
      strb.append("}");
      return strb.toString();
  }   
}

Output:

[{id: "RS02", name: "John", position: "HR"}, {id: "RS04", name: "Juliet", position: "Manager"}, {id: "RS03", name: "Robert", position: "Manager"}]

We have seen JSON with Java using JSON.simple. Now, let us see JSON with PHP. The following section will help you in performing encoding and decoding JSON objects with PHP. 

JSON with PHP

Like JavaScript, PHP is also a scripting language. The PHP scripting language is specially used for developing web applications. PHP implies Hypertext Processor. Earlier, PHP was known as Personal Home Page. 

How to use JSON with PHP? How to encode and decode JSON objects in PHP? Here is a short guide for you, explaining how to use PHP to encode and decode JSON objects. 

The first step you need to remember while using JSON objects with PHP is setting up the PHP environment. The JSON extension is already compiled with PHP 5.2.0. Hence, there are no additional steps required for setting up the PHP environment for using JSON. 

JSON Function in PHP

Here are some significant JSON functions to be used in PHP for encoding and decoding. 

  1. json_encode: When you pass a value to the json_encode function, it returns that value’s JSON form. 
  2. json_decode: This function decodes the JSON string. 
  3. json_last_error: As its name indicates, the json_last_error function returns the error that occurred the last time in the code. 

Encoding JSON in PHP

We have seen the json_encode() function above. Therefore, we use the json_encode() function to encode JSON objects in PHP. When you pass any value to this function, it produces a JSON representation of that value as its result on success. Else, it produces FALSE. 

Syntax:

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

Here, the value represents the data you need to encode. Remember that json_encode() function only supports UTF-8 encoded data. The second parameter in the above function is optional. It contains bitmask, like JSON_PRETTY_PRINT, JSON_HEX_QUOT, JSON_HEX_TAG, JSON_FORCE_OBJECT, JSON_NUMERIC_CHECK, JSON_HEX_APOS, etc.  

Let us understand encoding JSON objects in PHP with a straightforward example. 

Example:

<?php
class Employee {
public $id = " ";
public $name = " ";
public $position = " ";
public $city = " ";
}
$emp = new Employee();
$emp ->id = "RS02";
$emp->name = "John";
$emp->position = "Manager";
$emp->city = "California";
echo json_encode($emp);
?>

Output:

{"id": "RS02", "name": "John", "position": "Manager", "city": "California"}

Decoding JSON in PHP

We use json_decode() function for decoding JSON objects in PHP. It produces the output as the value in PHP, which is decoded from the JSON object. The below is the syntax of the json_decode() function. 

Syntax:

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

Here, $json is the json_string, which is to be decoded. This string should be UTF-8 encoded. Another parameter is assoc, which is a Boolean type. Depth implies the number of times the function should recurse. The last parameter is options, which is the bitmask. 

Let us observe one example of decoding JSON objects in PHP. 

Example:

<?php
$jsonStr = '{"Steve": 123, "John": 133, "Robert": 143, "Oliver": 153}';
var_dump(json_decode($jsonStr));
?>

Output:

object(stdClass)#1 (4) {
["Peter"] => int(123)
["John"] => int(133)
["Robert"] => int(143)
["Oliver"] => int(153)
}

This was all about encoding and decoding JSON objects in PHP. 

JSON with Python

This section will help you to encode and decode JSON objects in Python. Python is one of the popular high-level programming languages. Before starting to encode or decode JSON in Python, you have to set the Python environment first. 

The first step to use JSON with Python is to download any JSON module. For instance, if you choose the Demjson as the JSON module, follow the below commands:

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

There are several other JSON modules, like ‘marshal’, and ‘pickle’. There are two different functions for using JSON with Python, encode, and decode. The encode function encodes Python objects into JSON. The result is represented in the JSON String form. On the other hand, the decode function decodes the JSON String into a Python object. 

Encoding JSON in Python

We use the encode() function to transform the Python object into the JSON String. Below are the syntax and example of encoding JSON in Python. 

Syntax:

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

Example:

#!/usr/bin/python
import demjson
dataStr = [ {'Steve': 123, 'John': 133, 'Robert': 143, 'Oliver': 153} ]
jsnStr = demjson.decode(dataStr)
print jsnStr

Output:

[{"Steve": 123, "John": 133, "Robert": 143, "Oliver": 153}]

Decoding JSON in Python

For decoding JSON in Python, we use the decode() function. The result of the decode() function returns the Python object from the JSON String. Let us observe the syntax and example of the decode() function. 

Syntax:

demjson.decode(self, txt)

Example:

#!/usr/bin/python
import demjson
jsonStr = '{"Steve": 123, "John": 133, "Robert": 143, "Oliver": 153}';
txtStr = demjson.decode(jsonStr)
print txtStr

Output:

{u'Steve': 123, u'John': 133, u'Robert': 143, u'Oliver': 153}

This was all about encoding and decoding JSON objects in Python. You can also use JSON with Ruby and Perl programming languages. For both Ruby and Perl programming languages, you have to first set-up the environment and then perform encoding and decoding with JSON. 

Benefits of JSON

We have seen features and applications of JavaScript Object Notation (JSON). It is similar to the XML in terms of data interchanging in different environments. Here are some significant benefits of JSON. 

Conclusion

JavaScript Object Notation (JSON) holds the data in the text format, which is easily understandable by humans. The data in JSON is represented in attribute-value pairs or the array data structure. This post is a quick and complete guide for you about JSON. We have seen JSON, its features, and where to use JSON. There are six different types of JSON data types, Number, String, Array, Boolean, Null, and Object. Each of these JSON data types is explained with an example and its respective syntax. 

You know very well about creating JSON objects in numerous forms. JSON.simple is used for encoding and decoding JSON objects in Java. When you go through this post, you will understand how to set-up the JSON Java environment on your Windows, macOS, and Linux systems. In the later section, we have depicted several JSON examples. We have seen encoding JSON objects in Java and encoding JSON arrays in Java with examples. You can also observe the decoding of a JSON object in Java. 

Next, we have mentioned multiple examples of merging two arrays, combining two objects, the combination of primitives, object, array, the combination of primitives, map, list, and the combination of primitives, list, map, object. Lastly, we have discussed an example of the customized output. 

In the next section, we discussed JSON with Python and PHP. We have seen how to set-up the PHP and Python environments for JSON. Later, we have seen encoding and decoding JSON objects in PHP and Python with examples. 

Recommended Articles

Exit mobile version