我需要连接并从API获取数据(数据将采用JSON格式),然后以表格的形式存储数据。我使用python以JSON形式提取数据但现在当我以.csv格式转换它时,我得到错误为:TypeError:list indices必须是整数,而不是str。
我使用的代码如下:
import urllib2
import json
import csv
f = urllib2.urlopen('https://api.weather.com/v1/location/KORD:9:US/observations/historical.json?units=e&startDate=20140703&endDate=20140704&apiKey=742a31ced27a477045')
json_string = f.read()
x = json.loads(json_string)
f = csv.writer(open("test.csv", "wb+"))
# For CSV Headers
f.writerow(["obs_id", "obs_name", "temp", "valid_time_gmt"])
for x in x:
f.writerow([x["observations"]["obs_id"],
x["observations"]["obs_name"],
x["observations"]["temp"],
x["observations"]["valid_time_gmt"]])
f.close()
提取的JSON就像
> { "metadata": {
> "language": "en-US",
> "transaction_id": "1484310885350:-90975020",
> "version": "1",
> "location_id": "KORD:9:US",
> "units": "e",
> "expire_time_gmt": 1484314485,
> "status_code": 200 }, "observations": [
> {
> "key": "KORD",
> "obs_id": "KORD",
> "obs_name": "Chicago/O'Hare",
> "valid_time_gmt": 1404453060,
> "day_ind": "N",
> "temp": 61
> },
> {
> "key": "KORD",
> "obs_id": "KORD",
> "obs_name": "Chicago/O'Hare",
> "valid_time_gmt": 1404456660,
> "day_ind": "N",
> "temp": 60
> },....... and so on
请你帮忙解决一下需要改变的地方吗?