Python簡單解析和封裝json
阿新 • • 發佈:2019-01-02
python list物件轉換成json格式
#!/usr/bin/env python import json data = [{'type':'trigger','addr':'0x1234','data':'0x1234'}] print "data:", data json_str = json.dumps(data) print "json:", json_str 輸出結果: data: [{'data': '0x1234', 'type': 'trigger', 'addr': '0x1234'}] json: [{"data": "0x1234", "type": "trigger", "addr": "0x1234"}]
解析json
#!/usr/bin/env python
import json
s = json.loads('{"type":"trigger","addr":"0x1234","data":"0x5678"}')
print s
print s["type"]
print s["addr"]
print s["data"]
輸出結果
{u'data': u'0x5678', u'type': u'trigger', u'addr': u'0x1234'}
trigger
0x1234
0x5678