Python 解析 JSON 数组
Posted
技术标签:
【中文标题】Python 解析 JSON 数组【英文标题】:Python Parse JSON array 【发布时间】:2018-04-14 01:49:46 【问题描述】:我正在尝试编写一个可以从大型数据集中解析出数组的小型 python 脚本。我希望从每个对象中提取一些key:values
,以便稍后在脚本中播放它们。现在我只想打印结果。我已经成功地使用仅包含对象的 JSON 文件做到了这一点,但似乎无法让它适用于数组。任何提示将不胜感激
这是我的代码:
# 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)
这是示例 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"
]
]
【问题讨论】:
【参考方案1】:在您的for
循环语句中,json_array
中的每个item
都是一个字典,并且该字典没有键 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)
【讨论】:
谢谢@yklsga。 store_list 变量是否意味着是一个空数组来保存要解析的数据? 是的store_list
最初是一个空列表,因为我认为您想保留 json_array
中的商店顺序。我将每个人 store_details
添加到 store_list
,以便您以后可以按特定顺序使用它们
谢谢您的解释;仍在学习中,这很有帮助!以上是关于Python 解析 JSON 数组的主要内容,如果未能解决你的问题,请参考以下文章