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
0 Comments