【问题标题】:How to add a value to nested list in json?如何在json中添加附加值
【发布时间】:2022-11-26 11:30:34
【问题描述】:

我有一个 json 变量看起来像这样

json_data=

[
    {
        "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"
    }
]

谢谢

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

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

    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] 获取列表中的第一项,字典键返回它们各自的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-16
      • 1970-01-01
      • 2015-12-20
      • 2021-05-03
      • 2017-06-05
      • 2022-01-18
      • 1970-01-01
      相关资源
      最近更新 更多