繁体   English   中英

Python 检查 json 的键和值

[英]Python check json for keys and values

我正在尝试在 python 中编写一个代码,该代码将 json 文件作为输入。 它可以包含其他字典、列表等。我正在尝试打印它们的键,我的问题是具有相同名称的键我只打印了最后一个键和值。 嵌套键也打印为值。 最后,我使用 len() 来计算相同键出现的次数,但我的代码有问题...

代码:

#open data
import json

with open('list.txt') as f:
    my_dict = json.load(f)

    #find key
    for key, value in my_dict.items():
         print("Key : {}, Value : {}".format(key, value))

    print("\n")

    #how many time you found the key
    for key,value in my_dict.items():
         print("{} found : ".format(key),len(key))

Json 文本:

{
    "QQ": "text",
    "WW": "text",
    "EE": "text1",
    "EE": "text2",
    "EE": "text3",
    "RR": ["text", "text"],
    "TT": 99,
    "YY": {
        "QQ": ["text", "text"],
        "TT": 99
    }
}

Output:

Key : QQ, Value : text
Key : WW, Value : text
Key : EE, Value : text3
Key : RR, Value : ['text', 'text']
Key : TT, Value : 99
Key : YY, Value : {'QQ': ['text', 'text'], 'TT': 99}


QQ found :  2
WW found :  2
EE found :  2
RR found :  2
TT found :  2
YY found :  2

JSON 不允许您拥有多个具有相同键的键值对。 因此,它只允许您访问键值对的最近更新(即文件中的最后一个)版本。 如果您希望它们都可以通过"EE"访问,您应该将"text1""text2""text3"放在分配给"EE"的列表中。

暂无
暂无

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

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