python操作json的例子

作者:简简单单 2014-07-31

首先操作一下python中的字典,首先是空字典eth,在其中添加数据eth0,eth1并对应两个ip

>>> eth = {}
>>> eth['eth0'] = ’192.168.2.12′
>>> print eth
{‘eth0′: ’192.168.2.12′}
>>> eth['eth1'] = ’223.5.5.5′
>>> print eth
{‘eth1′: ’223.5.5.5′, ‘eth0′: ’192.168.2.12′}

json与python中dict互相转换,把dict转换成json-使用json.dumps(),将json转换为dict-使用json.loads()

>>> import json
>>> ethjson = json.dumps(eth)
>>> type(ethjson)

>>> print ethjson
{“eth1″: “223.5.5.5″, “eth0″: “192.168.2.12″}
>>> ethdict = json.loads(ethjson)
>>> type(ethdict)

>>> print ethdict
{u’eth1′: u’223.5.5.5′, u’eth0′: u’192.168.2.12′}
>>> print ethdict['eth0'], ethdict['eth1']
192.168.2.12 223.5.5.5

判断json里是否有某个key

if ‘text’ in post['caption'].keys():
if ‘text’ in post['caption']:
if ‘ipv4′ in output['ansible_facts'][ansible_int]:

相关文章

精彩推荐