Python,字符串到 JSON?

标签 python linux json

在 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/

相关文章:

python - 对 django 应用程序进行单元测试的良好方法/设计

python - Codefights, minesweeper, python, code almost working

python - Django View 中的图像路径是相对于目录而不是 MEDIA_URL

linux - 是否有我可以在内核中使用的函数列表?

c - linux中strtok定义的位置

python - 统计字符串中某个字符出现的次数

linux - 如何使用 | 获取多个信息grep?

Android Volley JsonObjectRequest 每次在移动数据上返回相同的响应

java - 如何在Java中解析JSON

c# - 使用 ASP.NET C# 解析 JSON 中的数组