Search code snippets, questions, articles...

Read JSON data in python

When you are working with JSON in your application and want to read and access JSON items in your Python code, you first need to convert it to Python collection. We convert the JSON data in Python readable format using json.loads() function.
import json

json_data = '[{"name": "Rick", "place": "New York"}]'

result = json.loads(json_data);

print(result[0])

print(result[0]['name'])
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

Output

{'name': 'Rick', 'place': 'New York'}
Rick

Given a JSON string in the above code example and we want to access the items of JSON data in our Python code. To do that:

1. Importing json module in our Python file.

import json

2. Define a string variable json_data that contains JSON string.

3. Converting the above JSON string to Python collection - List using json.loads() function and it will return the Python Collection that will be assigned to result named variable.

json.loads(json_data)

4. Access the first list item using result[0] and print it.

4. Access key from first list item dictionary using result[0]['name'] and print it.

import json

json_str = '["a", "b", "c", "d"]'

data = json.loads(json_str)

for item in data:
  print(item)

# -> a
# -> b
# -> c
# -> d
In the above code example, we are reading JSON data using json.loads() function and then applying for loop on the elements of converted data.
import json

json_str = '{"name": "Math", "score": 90}'

data = json.loads(json_str)

for key in data:
  print("{} is: {}".format(key, data[key]))

# -> name is: Math
# -> score is: 90
We have given a JSON string that contains a dictionary in the above code example. We are converting the string data to a Python dictionary using json.loads() and then looping through the dictionary using For loop.
Was this helpful?
0 Comments