In this tutorial I am going to give you some information on JSON and explain its use within various programming languages such as Python, Java, Javascript, etc.
Prerequisites
Before we start, you should take a look at our Javascript Tutorial Series and Ajax Tutorial. If you already know these or looked at them now, let's begin;
What is JSON?
JSON (JavaScript Object Notation) is a lightweight text-based standard designed for human-readable data communication.
- JSON has been extended from JavaScript.
- It is mostly used to transmit data between a server and web applications.
- Web services and APIs use JSON format to provide public data.
- JSON format is specifically structured and this helps to keep things organized and error free.
- JSON is language independent.
The following simple example shows how to use JSON to store information related to cell phones based on their brands and operating systems.
A Basic JSON Example:
{"phones":[
{
"Brand":"Apple",
"OS":"iOS"
},
{
"Brand":"Samsung",
"OS":"Android"
},
{
"Brand":"Motorola",
"OS":"Android"
}
]}
As you can see from the example above, data in JSON is represented in name/value pairs. In the first entry, 'Brand' name corresponds to value 'Apple'. Square brackets represent a JSON Array node and Curly braces represent a JSON Object Node.
The following example shows how JSON is used in an HTML page with JavaScript:
<!-- HTML Code to manipulate by JS -->
<p id="demo"></p>
//JavaScript Code
var text = '{"Brand":"Samsung","OS":"Android"}';
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.Brand + " devices use " + obj.OS + " operating system." ;
The Output (Click to View on Codepen):
Samsung devices use Android operating system.
JSON vs. XML
We already know what XML looks like from the AJAX tutorial which I advised you to take a look. Now let's investigate the commonalities and differences of these two.If we compare JSON with XML, we see a lot of common properties:
- They are both human readable (self describing),
- They are both hierarchical (values within values),
- Both can be parsed and used by various programming languages,
- Both can be fetched with an XMLHttpRequest.
- JSON doesn't use end tag
- JSON is shorter
- JSON is quicker to read and write
- JSON can use arrays
The biggest difference: XML has to be parsed with an XML parser. JSON can be parsed by a standard JavaScript function as we did in the previous example (JSON.parse()).
JSON with Other Programming Languages:
1 - JSON with Java
In order to be able to use JSON with Java we need to download and add a .jar file to our project directory (Download from here):
In this example we create an empty JSON object, then we populate this object by using the createJSON() method that we wrote, and then we print the result. Finally we convert this JSON format back into a form of single entries and print those as well.
package example;
import java.util.ArrayList;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JSONCodemio {
public static void main(String[] args) {
// Let's create an empty JSON object
JSONObject obj = new JSONObject();
ArrayList<Object> list = new ArrayList<>();
list.add("John");
list.add(33);
list.add(false);
// Give this object to our createJSON method
// to print JSON format and then decode this back into
// an array with decodeJSON method
decodeJSON(createJSON(obj,list));
}
/**
* Creates and prints the given ArrayList in JSON format
* @param json of type JSONObject
* @param a of type ArrayList<Object>
*/
public static String createJSON(JSONObject json, ArrayList<Object> a){
// Fill it with data
json.put("name", a.get(0));
json.put("age", a.get(1));
json.put("dead", a.get(2));
System.out.println("After Creating:");
System.out.println(json);
return json.toString();
}
/**
* Decodes a given JSON format string and prints
* @param s of type String
*/
public static void decodeJSON(String s){
JSONParser parser = new JSONParser();
try{
JSONObject object = (JSONObject) parser.parse(s);
// Note that JSONArray will be necessary
// if you have more than one entries in your JSON
System.out.println("\nAfter Decoding:");
System.out.println(object.get("name"));
System.out.println(object.get("dead"));
System.out.println(object.get("age"));
}catch(Exception e){
System.out.println(e);
}
}
}
And this is the Output: 2- JSON with Python
Before we start with encoding and decoding JSON using Python, we need to install any of the JSON modules available as shown below. (Download from here)
$ tar xvfz demjson-1.6.tar.gz
$ cd demjson-1.6
$ python setup.py install
The following example shows array encoding in JSON with Python:
#!/usr/bin/python
import demjson
data = [ { 'x' : 1, 'y' : 2, 'z' : 3, 'u' : 4, 't' : 5 } ]
json = demjson.encode(data)
print json
The Output:[{"x":1,"y":2,"z":3,"u":4,"t":5}]
The following example shows decoding in JSON with Python:
#!/usr/bin/python
import demjson
json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
text = demjson.decode(json)
print text
The Output:{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}
Alright everyone, you have reached the end of this tutorial. I hope you found it useful. Leave a comment below if you have any questions or comments. Happy Coding!
Disqus Comments Loading..