首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python解析JSON数组

Python解析JSON数组
EN

Stack Overflow用户
提问于 2017-11-02 01:03:10
回答 1查看 90.6K关注 0票数 21

我正在试着组合一个小的python脚本,它可以从一个大的数据集中解析出数组。我希望从每个对象中提取一些key:values,以便稍后在脚本中回放它们。现在,我只想打印结果。我已经成功地在只包含对象的JSON文件中做到了这一点,但似乎不能让它在数组中工作。任何建议我们都将不胜感激。

下面是我的代码:

代码语言:javascript
运行
复制
# 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数据:

代码语言:javascript
运行
复制
[
  {
    "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"
    ]}
  ]
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-11-02 01:19:35

在您的for循环语句中,json_array中的每个item都是一个字典,并且字典没有键store_details。所以我稍微修改了一下程序

代码语言:javascript
运行
复制
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)
票数 33
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47060035

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档