【发布时间】:2017-01-16 12:28:48
【问题描述】:
我需要从天气 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()行似乎“模仿”了使用“真实”内部文件对象,这是正确的吗?
非常感谢!
【问题讨论】:
-
你的第一个问题 - 检查 HTTP 标头,如果它有 application/json,它正在尝试提供 json :)
-
宾果游戏!它正在提供一个 json 文件! :) 所以,他们将带有
urlopen的文件提取到f,然后read()这个文件,这里变得很混乱......我应该将f保存到我的文件系统中吗?这个json_string是由于阅读获取的f?或者更进一步,可能在parsed_json = json.loads()之后? -
好像你需要解码你的json,stackoverflow.com/questions/12965203/…
-
如果您存储 json 只是为了模拟服务器并在其上练习 json,请不要担心它的外观,只担心是否可以加载它。 Json 作为一种格式转义了几乎所有 iirc
-
酷。我可以加载它和所有内容,但我想很好地重新格式化它,以便我也可以将它用作人类:)、检查位等。或者,我需要能够“很好地”打印到控制台...