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