【问题标题】:Python parsing json file into something usablePython将json文件解析成可用的东西
【发布时间】:2018-08-09 14:53:30
【问题描述】:

Python 2.7

我是 python 新手,这是我第一次寻求帮助。

我正在向网络发送一个发布请求并返回一个 json 文件。它看起来像这样:

json Example

如果我这样做:

打印数据['结果']

我列出了所有项目

如果我这样做:

打印数据['result']['recordtype']

我得到“列表索引必须是整数,而不是 str”(因为我需要 ['result'][0]['recordtype']?但这会将它限制为仅第一项)

我可以通过以下方式获得“一些”信息:

print(data['result'](类型为列表)

print(data['result'][0])(类型是字典)

print(data['result'][0]['columns'](type is a dict)

但这只会返回第一项。 ([0])。任何其他尝试都会给我一个“必须是整数而不是 str”。

最后,我想输入项目“id”并将该项目的所有属性“itemid”、“displayname”、“columns”等作为变量返回。 (“列”会因 json 文件而异,但其余应保持一致)

问题:

如何根据“id”值遍历所有这些项目并将与该项目关联的所有值作为变量返回?

【问题讨论】:

标签: python json


【解决方案1】:

【讨论】:

  • 我已经尝试了 json.dump/json.dumps - json.load/json.loads 的所有组合。
  • 如果我使用输出代码 "with open("C:\xxxx.json", "wb") 作为输出文件:json.dump(conn.text, codecs.getwriter('utf-8 ')(outfile), ensure_ascii=False)" 尝试使用“data = json.loads("C:\xxxx.json") 将其带回时,我得到 - “ValueError: No JSON object could be decoded”跨度>
  • 如果我使用 "data = json.load("C:\xxxxx.json")" 我得到 - "AttributeError: 'str' object has no attribute 'read'"
  • 如果我在输出代码上将“转储”更改为“转储”,则不会将任何内容写入文件。 (但没有错误)
  • 我通过将 "data = json.loads("C:\xxxxx.json")" 更改为 "data = json.loads(open("C:\xxxxx.json") .read())" 我现在可以加载 Json 文件了。
【解决方案2】:

我能够弄清楚一些事情。我把这个拼凑起来:

y = "user input id variable"
x = y

for i in data['result']: 
if i['id'] == x:
    NL_id = i['id']
    NL_Rc = i['recordtype']
    NL_Itid = i['columns']['itemid']
    break`

这会以我需要的方式从我需要的 json 字典中返回数据。也许这会帮助像我这样的其他人。 (python 的第五天 = 总菜鸟)。

【讨论】:

    【解决方案3】:

    使用 json python 库应该可以。 json 中的每个元素都是一个字典。对于每个字典,值可以是字符串、字典(等)或数组(元素集合)。 要使用键 k 访问字典的值,请执行 d['k']。如果它的值是一个数组,那么你指定索引:d['k'][0]

    以下面的json文件为例:

    {"menu": {
      "id": "file",
      "value": "File",
      "popup": {
        "menuitem": [
          {"value": "New", "onclick": "CreateNewDoc()"},
          {"value": "Open", "onclick": "OpenDoc()"},
          {"value": "Close", "onclick": "CloseDoc()"}
        ]
      }
    }}
    

    并使用此代码menuitem 是一个数组:

    import json
    
    f = open("test.json")
    a = f.read()
    jj = json.loads(a)
    print(a)
    print(type(jj))
    print(type(jj['menu']['popup']['menuitem']))
    for el in jj['menu']['popup']['menuitem']:
        print(el['value'])
    

    【讨论】:

      猜你喜欢
      • 2014-08-19
      • 2023-03-08
      • 2013-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多