我需要从天气 API 获取一些数据,提取某些信息并将其发送到 std。输出(在我的例子中,这是控制台/终端;我正在玩 python API 脚本,还没有网站/应用程序显示获取的数据)。
来自 API 提供者的示例 Python 代码(简单易懂且有效):
import urllib2
import json
API_KEY='mysuperawesomekey'
f = urllib2.urlopen('http://api.wunderground.com/api/' + API_KEY + '/geolookup/conditions/q/IA/Cedar_Rapids.json')
json_string = f.read()
parsed_json = json.loads(json_string)
location = parsed_json['location']['city']
temp_f = parsed_json['current_observation']['temp_f']
print "Current temperature in %s is: %s" % (location, temp_f)
f.close()
因为我是免费计划,所以我不想用完我的 API 请求,而是获取 JSON 数据,将其保存到文件中并在另一个脚本中使用来练习。我在 StackOverflow 上找到了几个解决方案但似乎都不能完全工作(文件格式很好):
尝试 1. 保存获取的数据,添加。到原点。上面的代码:
import io
import codecs
with open('data.json', 'w') as outfile:
json.dump(json_string, outfile, indent=4, sort_keys=True, separators=(",", ':'))
尝试 2:
with codecs.open('data.json', 'w', 'utf8') as jasonfile:
jasonfile.write(json.dumps(parsed_json, sort_keys = True, ensure_ascii=False))
我的两次尝试都成功了(“有点”),因为我得到了一个 .json 文件。但是,在我的编辑器 (Atom) 中检查它时,我看到了这一点(前几行软断行):
输出:
"\n{\n \"response\": {\n \"version\":\"0.1\",\n\"termsofService\":\"http://www.wunderground.com/weather/api/d/terms.html\",\n \"features\": {\n \"geolookup\": 1\n ,\n \"conditions\": 1\n }\n\t}\n\t\t,\t\"location\": {\n\t\t\"type\":\"CITY\",\n\t\t\"country\":\"US\",\n\t\t\"country_iso3166\":\"US\",\n\t\t\"country_name\":\"USA\",\n\t\t\"state\":\"IA\",\n\t\t\"city\":\"Cedar Rapids\",\n\t\t\"tz_short\":\"CDT\",\n\t\t\"tz_long\":\"America/Chicago\",\n\t\t\"lat\":\"41.97171021\",\n\t\t\"lon\":\"-91.65871429\",\n\t\t\"zip\":\...
全部在一行中,显示换行符和制表符。我有几个问题:
- 如何检查返回的数据类型 API 的格式/类型? (例如,它是否只是一个需要进行 JSON 验证的原始字符串?)
- 我的 JSON 是否由于编码、定界符错误而未以人类可读的格式编写?
- 示例代码中的
json_string = f.read()行似乎“模仿”了“真实的”内部文件对象,对吗?
非常感谢!
请您参考如下方法:
看起来这是一个非常简单的解决方案。在我的原始代码中,我将一个“未解析”变量保存到一个文件中:
import urllib2
import json
API_KEY='key'
f = urllib2.urlopen('http://api.wunderground.com/api/'
+ API_KEY + '/geolookup/conditions/q/IA/Cedar_Rapids.json')
# Saving the below variable into a .json file gives all the JSON data
# on a single line
json_string = f.read()
with open('data.json', 'w') as outfile:
json.dump(json_string, outfile, indent=4, sort_keys=True, separators=(",", ':'))
当然,这会生成一个包含一行 JSON 数据的文件。我应该做的是保存 parsed 变量:
import urllib2
import json
API_KEY='key'
f = urllib2.urlopen('http://api.wunderground.com/api/' + API_KEY + '/geolookup/conditions/q/IA/Cedar_Rapids.json')
json_string = f.read()
# THIS one is correct!
parsed_json = json.loads(json_string)
with open('data.json', 'w') as outfile:
json.dump(parsed_json, outfile, indent=4, sort_keys=True, separators=(",", ':'))
