在python中通过requests.get(url)获取json数据,此时可能需要eval进行解析。
1 # -*- coding: utf-8 -*- 2 import requests 3 4 r = requests.get(url='your url address') # 最基本的GET请求 5 # print r.content 6 # print '......................' 7 # print len(r.json() 8 # print '......................' 9 # print len(r.json()['data']) 10 # print '......................' 11 print r.json()['data'][6]['type'] # area 12 print '......................' 13 print r.json()['data'][6]['radarcoor'] 14 print '......................' 15 print r.json()['data'][6]['radarcoor'][0] # 错误 16 print '......................' 17 print eval("r.json()['data'][6]['radarcoor']")[0] # 错误 18 print '......................' 19 print eval("("+r.json()['data'][6]['radarcoor']+")")[0] # 正确的写法
此时r.json()返回:
r.json()['data'][6]['radarcoor']返回:
要获取其中每一项,则需要使用eval()函数进行解析:
2.json.dumps()
功能:将python中的数据类型转换成str类型
1 # json.dumps() 2 mylist = [123, {'name': 'dragon'}, {'location': ('ch', 'nt')}] 3 encoded_json = json.dumps(mylist) 4 print isinstance(encoded_json, str) # True 5 print encoded_json # [123, {"name": "dragon"}, {"location": ["ch", "nt"]}] 6 7 # json.loads() 8 # decoded_json = json.loads(encoded_json) 9 # print isinstance(decoded_json, list) # True 10 # print decoded_json # [123, {u'name': u'dragon'}, {u'location': [u'ch', u'nt']}] 11 12 # eval() 13 decoded_json = eval(encoded_json) 14 print isinstance(decoded_json, list) # True 15 print decoded_json # [123, {'name': 'dragon'}, {'location': ['ch', 'nt']}]