我想使用python生成以下json文件。
{
"type": "SubInterface",
"MTU": 1500,
"enabled": "True",
"vlanId": vlanid,
"subIntfId": subinterid,
"name": "abc",
"id": "intid",
"managementOnly": "False",
"activeMACAddress":"active-mac",
"standbyMACAddress":"standby-mac",
"securityZone": {
"name": "Zonename",
"id": "securityid",
"type": "SecurityZone"
},
"ifname": "interface-name",
"ipv4": {
"static": {
"address": ipv4address,
"netmask": "ipv4subnet"
}
},
"ipv6": {
"enableIPV6": "True",
"addresses": [
{
"address": ipv6address,
"prefix": "ipv6prefix",
"enforceEUI64": "False"
}
]
}
}
这是我的代码 -
import json
data={}
data["type"]="Subinterface"
data["MTU"]="1500"
data["enabled"]= "True"
data["vlanId"]="vlanid"
data["subIntfId"]="subinterid"
data["name"]= "Port-channel24"
data["id"]= "intid"
data["managementOnly"]= "False"
data["activeMACAddress"]="active-mac"
data["standbyMACAddress"]="standby-mac"
data['securityZone']=[]
data['securityZone'].append({
"name": "Zonename",
"id": "securityid",
"type": "SecurityZone"
})
data["ifname"]="interface-name"
data['ipv4']=[]
data['ipv4'].append({
data["static"]=[]
data["static"].append({
"address": "ipv4address",
"netmask": "ipv4subnet"
})
})
with open('data1.txt', 'w') as outfile:
json.dump(data, outfile)
执行它时会给我以下错误 -
automation) -bash-4.1$ python json23.py
File "json23.py", line 23
data["static"]=[]
^
SyntaxError: invalid syntax
如何使用嵌套值生成json
答案 0 :(得分:0)
这是因为您在上一行中有未闭合的括号:data['ipv4'].append({
。如果你关闭那些括号,你应该都很好。
答案 1 :(得分:0)
The problem is with this block:
data['ipv4']=[]
data['ipv4'].append({
data["static"]=[]
data["static"].append({
"address": "ipv4address",
"netmask": "ipv4subnet"
})
})
As a commented pointed out, your desired output does not have lists for ipv4
and static
. I suspect you want it to read:
data['ipv4'] = {
"static": {
"address": "ipv4address",
"netmask": "ipv4subnet"
}
}
Or if you insist on square bracket notation (though I'm not sure why you would):
data['ipv4'] = {}
data['ipv4']['static'] = {}
data['ipv4']['static']['address'] = 'ipv4address'
data['ipv4']['static']['netmask'] = 'ipv4subnet'
Some other notes:
append
to it - you can just initialise the list with the values that you want.dict
directly, instead of dynamically building it like here, is preferable where possible.