我无法遍历JSON文件以获取键的所有值。我尝试了多种写此错误的方法。
# Import package
from urllib.request import urlretrieve
# Import pandas
import pandas as pd
# Assign url of file: url
url = 'https://data.sfgov.org/resource/wwmu-gmzc.json'
# Save file locally
urlretrieve(url, 'wwmu-gmzc.json')
# Loading JSONs in Python
import json
with open('wwmu-gmzc.json', 'r') as json_file:
#json_data = json.load(json_file) # type list
json_data = json.load(json_file)[0] # turn into type dict
print(type(json_data))
# Print each key-value pair in json_data
#for k in json_data.keys():
# print(k + ': ', json_data[k])
for line in json_data['title']:
print(line)
#w_title = json_data['title']
#print(w_title)
for key, value in json_data.items():
print(key + ':', value)
#print(json_data.keys('title') + ':' , jason_data['title'])
此代码的当前版本仅给出文件的第一行:
<class 'dict'> 1 8 0 release_year: 2011 actor_2: Nithya Menon writer: Umarji Anuradha, Jayendra, Aarthi Sriram, & Suba locations: Epic Roasthouse (399 Embarcadero) director: Jayendra title: 180 production_company: SPI Cinemas actor_1: Siddarth actor_3: Priya Anand
以下已更正的代码,并说明了缺少的密钥:
# Loading JSONs in Python
import json
with open('wwmu-gmzc.json', 'r') as json_file:
content = json_file.read()
json_data = json.loads(content)
print(type(json_data))
for json_i in json_data:
try:
print(json_i['locations'])
except:
print('***** NO KEY FOUND *****')
答案 0 :(得分:0)
您仅在数据集中加载第一个数据。
with open('wwmu-gmzc.json', 'r') as json_file:
json_data = json.load(json_file) # Input is list of dict. So,load everything
for json_i in json_data:
print(json_i.get('your_key', 'default_value'))
答案 1 :(得分:0)
您的代码不起作用,因为您正在获取的数据实际上是一个列表。要读取列表中的每个项目(每个项目都是键值对),您可以这样做。
# Import package
from urllib.request import urlretrieve
import json
# Assign url of file: url
url = 'https://data.sfgov.org/resource/wwmu-gmzc.json'
# Save file locally
urlretrieve(url, 'wwmu-gmzc.json')
# Loading JSONs in Python
with open('wwmu-gmzc.json', 'r') as json_file:
content = json_file.read()
json_data = json.loads(content)
for item in json_data:
print('======')
for key, value in item.items():
print(key + ':', value)