gpt4 book ai didi

Python,字符串到 JSON?

转载 作者:太空狗 更新时间:2023-10-29 11:05:11 25 4
gpt4 key购买 nike

在 Fedora 17 64 位中使用 netifaces 和 json 导入。

我试图在 JSON 中获取这种格式

"net_info" : [
{"nic" : ..., "mac" : ..., "ip" : ...},
{"nic" : ..., "mac" : ..., "ip" : ...},
{"nic" : ..., "mac" : ..., "ip" : ...},
]

我目前正在使用一个 string 并只是附加到它,我得到了这个:

"'net_info': [{'nic':eth0,'mac':6c:f0:49:0f:e1:c2,'ip':192.168.1.116},]"

由于每个字符串开头和结尾的引号,这可能不起作用;有没有更好的方法来完成这个?我正在考虑使用字典列表,但最终还是先尝试使用字符串,但不确定在这种情况下哪种方式最好。

这是我的代码,包含 3 个列表:

def json_serialize(ip=[],mac=[],nic=[]):
jsonDump = "'net_info': ["
for i,item in enumerate(ip):
jsonDump += "{'interface_name':" + nic[i] +",'mac':"
+ mac[i] + ",'ip':" + ip[i] +"},"
jsonDump += "]"
print jsonDump.strip()

#Testing output after its passed in to json.dumps(), it now has quotes at beginning
#and end of string...?
print "\n"
print json.dumps(jsonDump)

最佳答案

只需创建一个包含 list 的 python dict,然后一次性将 that 转储到 JSON:

def json_serialize(ip, mac, nic):
net_info = []
for ipaddr, macaddr, nicname in zip(ip, mac, nic):
net_info.append({
'interface_name': nicaddr,
'mac': macaddr,
'ip': ipaddr
})
return json.dumps({'net_info': net_info})

您想要的输出格式似乎缺少外部 {} 括号以将其标记为正确的 JSON 对象。如果您真的必须生成该输出(因此缺少那些括号),只需再次删除它们:

print json_serialize(ip, mac, nic)[1:-1]

关于Python,字符串到 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13662399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com