How To Parse JSON Data In Python

The json library can parse JSON from strings or files. The library parses JSON format string and turns it into a Python dictionary or list. It can also convert Python dictionaries or lists to JSON string.

1. Parse JSON Format String To JSON Object.

Import python json library and invoke it’s loads method to parse JSON format string.

  1. The example JSON string is as following.
    json_string = '{"first_program": "Java", "last_program":"Python"}'
  2. Use below code to parse above JSON string.
    # first import json library.
    >>> import json
    >>> json_string = '{"first_program": "Java", "last_program":"Python"}'
    # use json library's loads method to parse json string and return json object.
    >>> parsed_json = json.loads(json_string)
    >>> parsed_json
    {'first_program': 'Java', 'last_program': 'Python'}
    # use the parsed json object as a python dictionary.
    >>> parsed_json['first_program']

2. Parse Python Dictionary Object To JSON String.

Invoke json library’s dumps method to convert python dictionary object to JSON string.

# first create a python dictionary object.
>>> dict_1 = {
...     'first_name': 'Richard',
...     'second_name': 'Trump',
...     'role': ['Administrator', 'Developer'],
... }
# convert the python dictionary object to json string.
>>> json_string = json.dumps(dict_1)
# print out the string
>>> print(json_string)
{"first_name": "Richard", "second_name": "Trump", "role": ["Administrator", "Developer"]}
# below error means the jsong_string is not a python dictionary object.
>>> json_string['first_name']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers

# the original dictionary object.
>>> dict_1['first_name']