In this tutorial we will be discussing on Python JSON; how to encode and decode JSON data using python. In our previous tutorial we discussed about Python raw_input.

python-json

Python JSON

Before starting with the Python’s json module, we will at first discuss about JSON data.

The abbreviation of JSON is JavaScript Object Notation.

According to Wikipedia, JSON is an open-standard file format that uses human-readable text to transmit data objects consisting of attribute-value pairs and array data types (or any other serializable value).

JSON a very common data format used for asynchronous browser/server communication. The Syntax rules for JSON is given below:

  1. The data is simply a name value pair
  2. Data/Object/arrays are separated by comma
  3. Curly braces hold object
  4. Square holds array

You may see some JSON data example here.

Python json dumps

In this section we will learn how to convert python data to JSON data. The task is very simple. At first import json module. Then use json.dumps() function to decode the json data. Below is a simple example for python json dumps function.


import json
# initialize different data
str_data="normal string"
int_data = 1
float_data = 1.50
list_data = [str_data, int_data, float_data]
nested_list = [int_data, float_data, list_data]
dictionary = {
    'int': int_data,
    'str': str_data,
    'float': float_data,
    'list': list_data,
    'nested list': nested_list
}
# convert them to JSON data and then print it
print('String :', json.dumps(str_data))
print('Integer :', json.dumps(int_data))
print('Float :', json.dumps(float_data))
print('List :', json.dumps(list_data))
print('Nested List :', json.dumps(nested_list, indent=2))
print('Dictionary :', json.dumps(dictionary, indent=2))  # the json data will be indented

You will get output like this.


String : "normal string"
Integer : 1
Float : 1.5
List : ["normal string", 1, 1.5]
Nested List : [
  1,
  1.5,
  [
    "normal string",
    1,
    1.5
  ]
]
Dictionary : {
  "int": 1,
  "str": "normal string",
  "float": 1.5,
  "list": [
    "normal string",
    1,
    1.5
  ],
  "nested list": [
    1,
    1.5,
    [
      "normal string",
      1,
      1.5
    ]
  ]
}
python-json

Python JSON pretty print

As you can see in above example, for json pretty print we have to pass an extra variable ‘indent’ to the json dumps function. For example json.dumps(nested_list, indent=2).

Python parse json – python json loads

You can easily parse JSON data to Python objects. By using json.loads() function you can simply convert JSON data into Python data. So, see the following python parse json example code to understand python json loads function.


import json
# initialize different JSON data
arrayJson = '[1, 1.5, ["normal string", 1, 1.5]]'
objectJson = '{"a":1, "b":1.5 , "c":["normal string", 1, 1.5]}'
# convert them to Python Data
list_data = json.loads(arrayJson)
dictionary = json.loads(objectJson)
print('arrayJson to list_data :n', list_data)
print('nAccessing the list data :')
print('list_data[2:] =', list_data[2:])
print('list_data[:1] =', list_data[:1])
print('nobjectJson to dictionary :n', dictionary)
print('nAccessing the dictionary :')
print('dictionary['a'] =', dictionary['a'])
print('dictionary['c'] =', dictionary['c'])

Below is the output of python parse json example program.


arrayJson to list_data :
 [1, 1.5, ['normal string', 1, 1.5]]
Accessing the list data :
list_data[2:] = [['normal string', 1, 1.5]]
list_data[:1] = [1]
objectJson to dictionary :
 {'a': 1, 'b': 1.5, 'c': ['normal string', 1, 1.5]}
Accessing the dictionary :
dictionary['a'] = 1
dictionary['c'] = ['normal string', 1, 1.5]
python-json

Python Object to JSON Data Conversion

In the previous two sections you may have noticed that Python List is converted into JSONArray data and Python Dictionary becomes the JSONObject. So which Python object is converted into JSON object by default is shown in the below table.

Python JSON
dict object
list, tuple array
str string
int, float, int- & float-derived Enums number
True true
False false
None null

Also, if you convert a JSONArray, you will get Python List. So, there are also some rules about this. So the following tables show the type of JSON data that are converted into Python Data.

JSON Python
object dict
array list
string str
number (int) int
number (real) float
true True
false False

So, that’s all about Python JSON module, python parse json examples. For any further query, please ask that in the comment section.

By admin

Leave a Reply

%d bloggers like this: