python-3.x 如何在json中增加附加值

yqkkidmi  于 2022-11-26  发布在  Python
关注(0)|答案(1)|浏览(133)

我有一个如下所示的json变量

json_数据=

[
    {
        "authType": "ldap",
        "password": "",
        "permissions": [
            {
                "collections": [
                    "aks9099",
                    "aks9098"
                ],
                "project": "Central Project"
            }
        ],
        "role": "devSecOps",
        "username": "chini.n@example.com"
    }
]

我想添加aks9100到集合
预期结果应如下所示

[
    {
        "authType": "ldap",
        "password": "",
        "permissions": [
            {
                "collections": [
                    "aks9099",
                    "aks9098",
                    "aks9100"
                ],
                "project": "Central Project"
            }
        ],
        "role": "devSecOps",
        "username": "chini.n@example.com"
    }
]

谢谢

8ulbf1ek

8ulbf1ek1#

以下是一种快速的非动态方法:

import json

json_path = '/Path/To/File.json'
# Open and read file
with open(json_path, 'r') as fin:
    json_data = json.load(fin)

# Open and write to file
with open(json_path, 'w') as fout:
    # Add str to nested list
    json_data[0]['permissions'][0]['collections'].append("aks9100")
    # Use write() and dumps() to maintain the json format
    fout.write(json.dumps(json_data, indent=4))

在上面我假设你需要更新一个json文件。在json数据中你有一个带有嵌套字典的列表和另一个嵌套在字典中的列表。[0]获取列表中的第一项,字典键返回各自的值。

相关问题