python 查找 JSON 中出现的所有键并修改值
python find all occurrences of key in JSON and modify value
我有以下问题。使用 Python 2.7,我有一个 JSON,我必须找到所有出现的键“workers”。
该值始终是整数列表
workers : [22,14,523,...]
我必须将它们与其他一些整数列表进行比较。
ID = [14,22,26,32,...]
如果工人列表中的 ID 列表中缺少一个号码,则必须删除工人中的号码。
我希望我说得够清楚了。
问题是这是一个不同级别的嵌套 JSON。
有什么建议吗?
谢谢
您可以在下面查看示例。我希望你的意思是类似的解决方案。
test_ids_1 = [1, 2, 3, 4, 5, 6]
test_ids_2 = [1, 2, 3, 4, 5, 8]
json_var = [
{
"human": {"man":
{"workers": [1, 2, 3],
"blabla": "abcd"},
"woman":
{"workers": [4, 5, 6],
"blabla": "dcab"}}
}
]
for worker in json_var[0]["human"]:
for ids in json_var[0]["human"][worker]["workers"]:
if ids not in test_ids_1:
print("%s is missing from test_ids_1 list" % ids)
if ids not in test_ids_2:
print("%s is missing from test_ids_2 list" % ids)
输出:
python test.py
6 is missing from test_ids_2 list
注意:当然,如果您读取 Json 文件并将其序列化,那么您可以对其进行迭代并检查元素。您可以查看有关此 link 的详细信息:https://docs.python.org/2/library/json.html
我有以下问题。使用 Python 2.7,我有一个 JSON,我必须找到所有出现的键“workers”。
该值始终是整数列表
workers : [22,14,523,...]
我必须将它们与其他一些整数列表进行比较。
ID = [14,22,26,32,...]
如果工人列表中的 ID 列表中缺少一个号码,则必须删除工人中的号码。
我希望我说得够清楚了。
问题是这是一个不同级别的嵌套 JSON。
有什么建议吗?
谢谢
您可以在下面查看示例。我希望你的意思是类似的解决方案。
test_ids_1 = [1, 2, 3, 4, 5, 6]
test_ids_2 = [1, 2, 3, 4, 5, 8]
json_var = [
{
"human": {"man":
{"workers": [1, 2, 3],
"blabla": "abcd"},
"woman":
{"workers": [4, 5, 6],
"blabla": "dcab"}}
}
]
for worker in json_var[0]["human"]:
for ids in json_var[0]["human"][worker]["workers"]:
if ids not in test_ids_1:
print("%s is missing from test_ids_1 list" % ids)
if ids not in test_ids_2:
print("%s is missing from test_ids_2 list" % ids)
输出:
python test.py
6 is missing from test_ids_2 list
注意:当然,如果您读取 Json 文件并将其序列化,那么您可以对其进行迭代并检查元素。您可以查看有关此 link 的详细信息:https://docs.python.org/2/library/json.html