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
}
}
输出:
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"
、"text2"
和 "text3"
都可以通过 "EE"
.[=15= 访问,则应将它们放在分配给 "EE"
的列表中]
我正在尝试在 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
}
}
输出:
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"
、"text2"
和 "text3"
都可以通过 "EE"
.[=15= 访问,则应将它们放在分配给 "EE"
的列表中]