获取json列表文件python中key的所有值

问题描述 投票:0回答:2

我无法迭代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
2个回答
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'))

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)

© www.soinside.com 2019 - 2024. All rights reserved.