在Fedora 17 64bit的同時使用netifaces和json導入。Python,字符串到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)
你所生產不是有效的JSON。對於初學者,你需要一個'{'..'}'。 –