我有一个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"
}
]谢谢
发布于 2022-11-26 02:56:12
下面是一种快速的非动态方法:
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]获取列表中的第一项,字典键返回各自的值。
发布于 2022-11-26 17:31:29
要将"aks9100"添加到这个特定的json变量中,您需要使用以下代码:
import json
json_data[0]['permissions'][0]['collections'].append("aks9100")https://stackoverflow.com/questions/74568785
复制相似问题