Python简单解析和封装json

2023-01-31 02:01:57 简单 解析 封装

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


相关文章