Python, string to JSON?

Python, string to JSON? … here is a solution to the problem.

Python, string to JSON?

Use netifaces and JSON import in Fedora 17 64-bit.

I’m trying to get this format in JSON

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

I’m currently using a string and just appending to it, I got this :

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

This may not work due to quotation marks at the beginning and end of each string; Is there a better way to accomplish this? I’m thinking about using a dictionary list, but ended up trying strings first, but not sure which way is best in this case.

Here is my code with 3 lists:

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)

Solution

Just create a python dict containing a list and dump that to 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})

The output format you want seems to be missing external { and } brackets to mark it as the correct JSON object. If you really have to generate that output (hence those missing brackets), just remove them again:

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

Related Problems and Solutions