How to Access Nested JSON Data in Python: A Step-by-Step Guide
This article explains how to correctly access nested data within a JSON file using Python. It identifies common errors and provides corrected code examples for accessing the value of 'site2' from a sample JSON file.
Question:
I have a JSON file 'file.json' as follows:
{
'name':'runoob',
'alexa':10000,
'sites': {
'site1':'www.runoob.com',
'site2':'m.runoob.com',
'site3':'c.runoob.com'
}
}
Can I use the following 2 codes in Python to query the value of 'site2'?
Code 1:
import json
# load the JSON file
with open('file.json') as f:
# access the value of 'site2'
site2 = f.sites.site2
print(site2)
Code 2:
import json
# load the JSON file
with open('file.json') as f:
# access the value of 'site2'
site2 = f['sites']['site2']
print(site2)
Answer:
No, both codes will not work as they have some syntax errors.
Code 1 Error:
After opening the JSON file, you need to parse the JSON data using the json.load() function to convert it into a Python object. Also, to access the value of 'site2', you need to use the dictionary syntax for nested objects. So the correct code would be:
import json
# load the JSON file
with open('file.json') as f:
data = json.load(f)
# access the value of 'site2'
site2 = data['sites']['site2']
print(site2)
Code 2 Error:
You are trying to access the 'sites' property of the file object f, which is not possible as it is just a file handle. So you need to parse the JSON data first using json.load(). The correct code would be:
import json
# load the JSON file
with open('file.json') as f:
data = json.load(f)
# access the value of 'site2'
site2 = data['sites']['site2']
print(site2)
By using json.load(), you convert the JSON data into a Python dictionary, enabling you to access its elements using the dictionary syntax.
原文地址: https://www.cveoy.top/t/topic/osnE 著作权归作者所有。请勿转载和采集!