【问题标题】:python find all occurrences of key in JSON and modify valuepython在JSON中查找所有出现的键并修改值
【发布时间】:2016-03-23 14:06:51
【问题描述】:

我有以下问题。使用 Python 2.7,我有一个 JSON,我必须找到所有出现的关键“工人”。

值始终是整数列表

   workers : [22,14,523,...]

我必须将它们与其他一些整数列表进行比较。

 ID = [14,22,26,32,...]

如果工人列表中的一个号码从 ID 列表中丢失,则必须删除工人中的号码。

我希望我已经说得够清楚了。

问题是这是一个嵌套的 JSON 有不同的层次。

有什么建议吗?

谢谢

【问题讨论】:

    标签: python json find compare key


    【解决方案1】:

    您可以在下面看到一个示例。我希望你的意思是类似的解决方案。

    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 文件并对其进行序列化,那么您可以对其进行迭代并检查元素。您可以在此链接上查看详细信息:https://docs.python.org/2/library/json.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-12
      • 1970-01-01
      • 1970-01-01
      • 2018-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多