【问题标题】:Python AND JSON ParsingPython 和 JSON 解析
【发布时间】:2015-05-20 13:46:51
【问题描述】:

我是 python 或 JSON 的新手。我有一个包含 JSON 数据的文件。

当我试图读取文件文件时。 “项目”是文件的关键。我使用了以下 python 脚本:

data=pandas.read_json('fileName.json') #using pandas
df=pandas.DataFrame(data) or json.loads #-> to read the file
print df.get('Items', {}) #-> to read entire file 
print df['Items'][0]['Patron'] #-> I can read an individual Patron like at '0' or '100'. But I want to generate the list of all 'patron' from the list. How do I do that? Any advise? 

如果我删除 [0],我会得到 Key 错误或其他东西。我确信它是因为无法访问字典。有什么办法可以解决吗?

{"Items": [{
  "Activity": "search.api",
  "Library": 1531,
  "Patron": 583586,
  "Tag": "browse-eaudio-religion",
  "Items": [
    "mediatype:eaudio",
    "genre:religion",
    "libraryid:1531",
    "ownership:owned",
    "usertype:patron",
    "page-count:5",
    "page-index:0",
    "page-size:60",
    "resultset-count:290",
    "sort:"
  ],
  "SearchType": "browse",
  "MediaType": "eaudio",
  "Genre": "religion",
  "NamedQuery": null,
  "Input": null,
  "ResultsetCount": 290,
  "Year": 2015,
  "Month": 4,
  "Day": 0,
  "Hour": 13
},{
  "Activity": "search.api",
  "Library": 985,
  "Patron": 674919,
  "Tag": "quick-author",
  "Items": [
    "libraryid:985",
    "ownership:owned",
    "usertype:patron",
    "page-count:93",
    "page-index:0",
    "page-size:60",
    "resultset-count:5552",
    "sort:author"
  ],
  "SearchType": null,
  "MediaType": "",
  "Genre": "",
  "NamedQuery": null,
  "Input": null,
  "ResultsetCount": 5552,
  "Year": 2015,
  "Month": 4,
  "Day": 0,
  "Hour": 13
}

【问题讨论】:

  • Khelweed3- Klaus 下面的回答解决了这个问题。谢谢你的时间
  • 为什么使用 pandas 而不是内置的 json 模块?
  • P.R.10- 我实际上都试过了。使用 Pandas 只是简化了我的统计分析 :-)

标签: python json


【解决方案1】:
patron_list = [item.get('Patron') for item in df['Items']]

【讨论】:

  • 这太棒了。谢谢克劳斯。
【解决方案2】:
# this is your data, simplified a bit,
# and indented for better readability:
data = {
    "Items": [
        {
          "Activity": "search.api",
          "Library": 1531,
          "Patron": 583586,
          "Tag": "browse-eaudio-religion",
        },
        {
          "Activity": "search.api",
          "Library": 985,
          "Patron": 674919,
          "Tag": "quick-author",
        }
    ]
}

# so you want 'Patron' field from every element in list data['Items']

# you can use list comprehension for this:
patrons = [item['Patron'] for item in data['Items']]

print patrons
# output:
# [583586, 674919]

【讨论】:

    猜你喜欢
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-11
    • 2013-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多