首先操作一下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(),json.loads()返回的是一个dictionary.
>>> 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(): #在keys中是否有text
if 'text' in post['caption']: # 在caption下是否有text
if 'ipv4' in output['ansible_facts']['ansible_int']: # 在ansible_facts下的ansible_int下是否有ipv4
有时候需要临时生成一个格式化过的json,可以使用json.tool模块来格式化
echo '{"json":"obj"}' | python -m json.tool
{
"json": "obj"
}