3

In Fedora 17 64bit while using netifaces and json imports.

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, and I get this:

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

This may not work due to the quotes at the beginning and the end of each string; is there a better way of accomplishing this? I was thinking of using a List of Dictionaries but ended up trying strings first, not sure what would best in this case.

Here's my code that takes in 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)
1
  • What you are producing is not valid JSON. You'd need a {..} around it for starters. Commented Dec 1, 2012 at 18:31

1 Answer 1

4

Just create a python dict with a contained list instead, then dump that to JSON in one go:

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})

Your desired output format seems to be missing the outer { and } brackets to mark it a proper JSON object. If you really have to produce that output (so missing those brackets), just remove them again:

print json_serialize(ip, mac, nic)[1:-1]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that was an extremely fast response and a valid one too!! :) Take care, i will accept this answer ASAP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.