简体   繁体   English

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

[英]get all values for key in json list file python

I can't iterate over a JSON file to get all values for a key. 我无法遍历JSON文件以获取键的所有值。 I've tried multiple ways of writing this with many errors. 我尝试了多种写此错误的方法。

# 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']) 

The current version of this code only gives the first line of the file: 该代码的当前版本仅给出文件的第一行:

<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

Corrected code below and accounts for missing keys: 更正了下面的代码,并说明了缺少键的原因:

# 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 *****')

You are loading only first data in the dataset. 您仅在数据集中加载第一个数据。

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'))

Your code does not work because the data your are fetching is actually a list. 您的代码不起作用,因为您正在获取的数据实际上是一个列表。 To read each item in the list (each item is a key-value pair) you can do. 要读取列表中的每个项目(每个项目都是键值对),您可以执行。

# 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM