如何更改json文件的某些值?

sg24os4d  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(335)

我有一个json文件,它是dic的列表。例如,它的两个要素是:

[{'key': 'chief information security officer',
  'top_transitions': [{'security architect': 5.0},
   {'cyber security manager': 3.0},
   {'information security officer': 3.0}]},
 {'key': 'security auditor',
  'top_transitions': [{'information security analyst': 9.0},
   {'information security officer': 9.0},
   {'it auditor': 6.0}]}]

我需要改变 top_transitions 以我的手为例,我可以怎样改变 {'security architect': 5.0}{'student': 15.0} ?

qxgroojn

qxgroojn1#

你可以用这个例子来改变 {"security architect": 5.0}{"student": 15.0} ( data 从json文件加载):

import json

to_search = {"security architect": 5.0}
to_replace = {"student": 15.0}

for item in data:
    if to_search in item["top_transitions"]:
        item["top_transitions"].remove(to_search)
        item["top_transitions"].append(to_replace)

print(json.dumps(data, indent=4))

印刷品:

[
    {
        "key": "chief information security officer",
        "top_transitions": [
            {
                "cyber security manager": 3.0
            },
            {
                "information security officer": 3.0
            },
            {
                "student": 15.0
            }
        ]
    },
    {
        "key": "security auditor",
        "top_transitions": [
            {
                "information security analyst": 9.0
            },
            {
                "information security officer": 9.0
            },
            {
                "it auditor": 6.0
            }
        ]
    }
]

相关问题