所以我想要做的是使用预先存在的文件在python中反向工程JSON对象。文件内容如下所示:创建一个符合python中特定JSON的JSON对象
[
{
"id": "PA_vnf",
"name": "PA",
"short-name": "PA",
"description": "A firewall PaloAlto",
"version": "1.0",
"connection-point": [
{
"type": "VPORT",
"name": "PA/cp0"
},
{
"type": "VPORT",
"name": "PA/cp1"
},
{
"type": "VPORT",
"name": "PA/cp2"
}
],
"vdu": [
{
"id": "pa_vdu",
"external-interface": [
{
"virtual-interface": {
"type": "VIRTIO"
},
"vnfd-connection-point-ref": "PA/cp0",
"name": "eth0"
},
{
"virtual-interface": {
"type": "VIRTIO"
},
"vnfd-connection-point-ref": "PA/cp1",
"name": "eth1"
},
{
"virtual-interface": {
"type": "VIRTIO"
},
"vnfd-connection-point-ref": "PA/cp2",
"name": "eth2"
}
],
"guest-epa": {
"cpu-pinning-policy": "ANY"
},
"name": "vdu-1",
"vm-flavor": {
"storage-gb": 40,
"memory-mb": 4096,
"vcpu-count": 4
},
"image": "paloAlto_RIP"
}
],
"service-function-chain": "UNAWARE",
"meta": "important info"
}
]
只是把事情简单化,对于现在我硬编码的所有键的值,如下图所示的代码示例:
def create_vnf_new():
ginfo = nested_dict(5,list)
ginfo['description'] = 'A firewall PaloAlto'
ginfo['name'] = 'PA'
ginfo['id']= 'PA_vnf'
ginfo['version'] = '1.0'
ginfo['service-function-chain'] = 'UNAWARE'
ginfo['short-name'] = 'PA'
ginfo['vdu']['id'] = 'pa_vdu'
ginfo['vdu']['name'] = 'vdu-1'
ginfo['vdu']['image'] = 'paloAlto_RIP'
ginfo['vdu']['guest-epa']['cpu-pinning-policy'] = 'ANY'
ginfo['vdu']['external-interface']['virtual-interface']['type'] = 'VIRTIO'
ginfo['vdu']['external-interface']['vnfd-connection-point-ref'] = "PA/cp0"
ginfo['vdu']['external-interface']['name'] = 'eth0'
ginfo['vdu']['vm-flavor']['storage-gb'] = 20
ginfo['vdu']['vm-flavor']['memory-mb'] = 1024
ginfo['vdu']['vm-flavor']['vcpu-count'] = 4
print(json.dumps(ginfo))
def nested_dict(n, type):
if n == 1:
return defaultdict(type)
else:
return defaultdict(lambda: nested_dict(n-1, type))
为此我得到下面的O/P:
{
"short-name": "PA",
"vdu": {
"name": "vdu-1",
"image": "paloAlto_RIP",
"id": "pa_vdu",
"external-interface": {
"virtual-interface": {
"type": "VIRTIO"
},
"vnfd-connection-point-ref": "PA/cp0",
"name": "eth0"
},
"guest-epa": {
"cpu-pinning-policy": "ANY"
},
"vm-flavor": {
"storage-gb": 20,
"vcpu-count": 4,
"memory-mb": 1024
}
},
"description": "A firewall PaloAlto",
"version": "1.0",
"service-function-chain": "UNAWARE",
"id": "PA_vnf",
"name": "PA"
}
以上的O/P是完全正常的,但我想某些属性,如“外部接口”有哪些我不能够做多个值。我尝试了字典上的append方法,但它一直在抛出错误“'collections.defaultdict'object has no attribute'append''。 示例追加我使用:ginfo ['vdu'] ['external-interface'] ['vnfd-connection-point-ref']。append(“value”)
我不确定发生了什么问题。另外我如何获得输出中的第一个方括号,这在我的o/p中是缺少的。我知道它应该是一个数组,但是,我不知道如何应用我的字典对象上的数组逻辑。
如果解释不够清楚,请让我知道,因为我在约5个小时的运气过后输入此帮助。