Python解析JSON数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47060035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Parse JSON array
提问by RomeNYRR
I'm trying to put together a small python script that can parse out array's out of a large data set. I'm looking to pull a few key:values
from each object so that I can play them back later on in the script. For now I just want to print the results. I've had success doing this with JSON files that only contained objects, but can't seem to get it working for an array. Any tips would be greatly appreciated
我正在尝试组合一个可以从大型数据集中解析出数组的小型 python 脚本。我希望key:values
从每个对象中提取一些,以便稍后在脚本中播放它们。现在我只想打印结果。我已经成功地使用仅包含对象的 JSON 文件执行此操作,但似乎无法使其适用于数组。任何提示将非常感谢
Here's my code:
这是我的代码:
# Load up JSON Function
import json
# Open our JSON file and load it into python
input_file = open ('stores-small.json')
json_array = json.load(input_file)
# Create a variable that will take JSON and put it into a python dictionary
store_details = [
["name"],
["city"]
]
# Learn how to loop better =/
for stores in [item["store_details"] for item in json_array]
# Print my results
print(store_details)
Here's the sample JSON Data:
这是示例 JSON 数据:
[
{
"id": 1000,
"type": "BigBox",
"name": "Mall of America",
"address": "340 W Market",
"address2": "",
"city": "Bloomington",
"state": "MN",
"zip": "55425",
"location": {
"lat": 44.85466,
"lon": -93.24565
},
"hours": "Mon: 10-9:30; Tue: 10-9:30; Wed: 10-9:30; Thurs: 10-9:30; Fri: 10-9:30; Sat: 10-9:30; Sun: 11-7",
"services": [
"Geek Squad Services",
"Best Buy Mobile",
"Best Buy For Business"
]
},
{
"id": 1002,
"type": "BigBox",
"name": "Tempe Marketplace",
"address": "1900 E Rio Salado Pkwy",
"address2": "",
"city": "Tempe",
"state": "AZ",
"zip": "85281",
"location": {
"lat": 33.430729,
"lon": -111.89966
},
"hours": "Mon: 10-9; Tue: 10-9; Wed: 10-9; Thurs: 10-9; Fri: 10-10; Sat: 10-10; Sun: 10-8",
"services": [
"Windows Store",
"Geek Squad Services",
"Best Buy Mobile",
"Best Buy For Business"
]}
]
回答by yash
In your for
loop statement, Each item
in json_array
is a dictionary and the dictionary does not have a key store_details
. So I modified the program a little bit
在你的for
循环语句中, Each item
injson_array
是一个字典,字典没有 key store_details
。所以我稍微修改了程序
import json
input_file = open ('stores-small.json')
json_array = json.load(input_file)
store_list = []
for item in json_array:
store_details = {"name":None, "city":None}
store_details['name'] = item['name']
store_details['city'] = item['city']
store_list.append(store_details)
print(store_list)