简体   繁体   English

如何从python中的json文件的特定键获取字段和值

[英]how to get fields and values from a specific key of json file in python

I am trying to return the fields and values of a specific key but getting error Here is the sample json format: 我正在尝试返回特定键的字段和值,但出现错误,这是示例json格式:

"results": [
    {
      "time": "00:00",
      "app_name": "dcg",
      "avg": "7717"
    },
    {
      "time": "00:00",
      "app_name": "pds",
      "avg": "75.40223463687151"
    },
    {
      "time": "00:00",
      "app_name": "rdts",
      "avg": "1481.5555555555557"
    },
    {
      "time": "00:00",
      "app_name": "slbl",
      "avg": "786"
    },
    {
      "time": "01:00",
      "app_name": "pds",
      "avg": "36.4765625"
    }

here is my code 这是我的代码

import json

json_data=open("some.json")
jdata = json.load(json_data)

for k, v in jdata.results.items():
    for k1, v1 in v.items():
        print(k1)
            print(v1)

Please note results is key and time field having multiple entries with same value. 请注意,结果是键和时间字段,其中包含多个具有相同值的条目。

Apart from fixing the broken indent, you can try the following. 除了修复损坏的缩进,您还可以尝试以下方法。 results is a key of your dictionary whose value can be accessed as jdata["results"] . results是字典的键,其值可以作为jdata["results"]进行访问。

for v in jdata["results"]:
    for k1, v1 in v.items():
        print(k1)
        print(v1)

EDIT : To store them in a list, you can do 编辑 :要将它们存储在列表中,您可以执行

result = []

for v in jdata["results"]:
    for k1, v1 in v.items():
        result.append({"k1":v1})

[{'k1': '00:00'},
 {'k1': 'dcg'},
 {'k1': '7717'},
 {'k1': '00:00'},
 {'k1': 'pds'},
 {'k1': '75.40223463687151'},
 {'k1': '00:00'},
 {'k1': 'rdts'},
 {'k1': '1481.5555555555557'},
 {'k1': '00:00'},
 {'k1': 'slbl'},
 {'k1': '786'},
 {'k1': '01:00'},
 {'k1': 'pds'},
 {'k1': '36.4765625'}]        

I had to put your JSON in a containing set of brackets {} otherwise the JSON processor can't parse it.... 我必须将您的JSON放在一组包含括号的{}中,否则JSON处理器无法解析它。

ie.. 即..

{ 'result' : [...] }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM