如何从API获取JSON数据,格式化/编码/写入文件?

时间:2016-09-08 14:10:27

标签: python json

我需要从天气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\":\...

全部在一行上,显示换行符和标签。我有几个问题:

  1. 如何查看返回的数据类型API的格式/类型? (例如,它只是一个需要JSON-iffied的原始字符串?)
  2. 由于编码,分隔符错误,我的JSON是不是以人类可读的格式编写的?
  3. 示例代码中的行json_string = f.read()似乎“模仿”使用“真正的”内部文件对象,这是正确的吗?
  4. 非常感谢!

1 个答案:

答案 0 :(得分:1)

似乎这是一个非常简单的解决方案。在我的原始代码中,我将“未解析”变量保存到文件中:

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=(",", ':'))

当然,这导致了一行中包含JSON数据的文件。我应该做的是保存解析的变量:

  <a href="#" onclick="OpenPopup(this)" id='<%# Eval("YolcuId") %>'>Sil</a> 
相关问题