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'])
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
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
- How to read a JSON file in Python
- [Python] Use json.dumps() to pretty-print Python dicts
- Convert JSON string to Python collections - like list, dictionaries
- Convert Python Collections - List, Dict to JSON String
- Convert List of Tuples to JSON string in Python
- [Python] Save (write) data to file
- Send post request with data and headers Python requests