While working with the Web Applications, REST APIs or document databases (eg. Oracle Autonomous JSON Database) we always deals with JSON. What is JSON & why its ideal data interchange format. Lets explore!

JSON – Java Script Object Notation

  • Derived from JavaScript.
  • Language independent text format for structuring data.
  • Light weight, easy to read/parse information.
  • Almost all language support this format eg. Python, R, Java, PL/SQL etc.
  • File extension: .json
  • Internet MIME Type: application/json

JSON is built using: Key Value Pair & Array – Ordered elements

  • Key:Value Pair ( Like Hash Map, Dict in Python, Associative array in PL/SQL)
  • Ordered list of values. (Array, List) example [1,2,3]

Sampe JSON:

{
  "firstName": "Calos",
  "lastName": "Smith",
  "isAlive": true,
  "age": 33,
  "address": {
    "streetAddress": "XYZ Street",
    "city": "New York",
    "state": "NY",
    "postalCode": "10021-3100"
  },
  "phoneNumbers": [
    {
      "type": "home",
      "number": "111 111-1234"
    },
    {
      "type": "office",
      "number": "111 555-4567"
    }
  ],
  "children": ["alex","marry"],
  "spouse": null
}

Some JSON Fundamentals

  • Key: Always string (double quotes only)
  • Value: String (double quotes only), Number, Bool (true/False), Object or List & Null.
  • Object: Unordered set of key value pairs. Object begins with { & ends with }. Inside object – Key:Value (key followed by a colon followed by the value always) separated by comma ex. { key1:par1, key2:pair2 }
  • Array: Ordered collection of values. Start with [ & ends with ]. Values separated by comma. [1,2,3,4] or [“A”, “B”,”C”,”D”].

See below example :

  • address is object – As it contains key values pairs. Example of nested object also as address is inside one big object.
  • children is example of array – you can access elements with index like children[0]
  • phoneNumbers . Objects inside Array.
{
	"age": 33,
	"address": {
		"streetAddress": "XYZ Street",
		"city": "New York",
		"state": "NY",
		"postalCode": "10021-3100"
	},
	"phoneNumbers": [{
			"type": "home",
			"number": "111 111-1234"
		},
		{
			"type": "office",
			"number": "111 555-4567"
		}
	],
	"children": ["alex", "marry"]
}

Python In-Built Module JSON

De-serialization – Decoding JSON data into python native datatype dict.

a) Reading JSON Data from API & converting it to Python Dictionary

import json
import requests

url = 'https://api.publicapis.org/entries'
req = requests.get(url)
text = req.text
print (type(text)) 

# json.loads - It will create a Python Dictionary
parsed_dict = json.loads(text)
print (type(parsed_dict))
print ((parsed_dict['entries'][2]))

Other example: Normal JSON String. Converting back to Python Dict

import json

normal_json_str = '{"id":101,"parent_id":null, "name":"XYZ", "is_owner":true}'
print(normal_json_str)
print(type(normal_json_str))

# json.loads - It will create a Python Dictionary
parsed_dict = json.loads(normal_json_str)

print(parsed_dict)
print(type(parsed_dict))

b) Reading JSON Data from file & converting it to Python Dictionary

import json

with open('sampledata.json') as f:
    data = json.load(f)
    print (type(data))
    print ((data['entries'][2]))

Serialization – Encoding data into native JSON.

a) Converting Python List to JSON Data & printing it. Output is string

import json

my_dict = { 'Aphabets' : { 'A':{'Fruit':'Apple','Object':'Aeroplane'},'B':{'Fruit':'Banana','Object':'Ball'}} , 
             'Numbers'  : {  0:'Zero', 1:'One'} 
           } 
print(type(my_dict))

print(json.dumps(my_dict, indent=4))

b) Converting Python List to JSON Data & saving it as file.

import json

my_dict = { 'Aphabets' : { 'A':{'Fruit':'Apple','Object':'Aeroplane'},'B':{'Fruit':'Banana','Object':'Ball'}} , 
             'Numbers'  : {  0:'Zero', 1:'One'} 
           } 
print(type(my_dict))

json.dump(my_dict, open ('jsonndata.json', 'w'), indent=4)

I have used jsonlint.com for validating JSON.

References:


Thanks!
Happy Learning! Your feedback would be appreciated!

One thought on “What is JSON?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s