【发布时间】:2019-01-23 03:13:02
【问题描述】:
我无法遍历 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 *****')
【问题讨论】:
标签: python json python-3.x dictionary