来自Python的post请求中的JSON查询,并将结果保存为csv文件

时间:2014-08-12 14:19:48

标签: python json csv post python-3.x

我正在尝试编写一个将连接到指定网址的程序:

http://api.scb.se/OV0104/v1/doris/sv/ssd/START/BO/BO0104/BostadsbestandK

并使用此查询:

{ "query": [ { "code": "Region", "selection": { "filter": "vs:RegionRiket99", "values": [ "00" ] } }, { "code": "Hustyp", "selection": { "filter": "item", "values": [ "FLERBO", "SMÅHUS" ] } }, { "code": "Tid", "selection": { "filter": "item", "values": [ "2012" ] } } ], "response": { "format": "csv" } }

然后我想将结果存储到csv文件中。

这是我到目前为止的代码:

import urllib.request
import json

url = 'http://api.scb.se/OV0104/v1/doris/sv/ssd/START/BO/BO0104/BostadsbestandK'

data = '{ "query": [ { "code": "Region", "selection": { "filter": "vs:RegionRiket99", "values": [ "00" ] } }, { "code": "Hustyp", "selection": { "filter": "item", "values": [ "FLERBO", "SMÅHUS" ] } }, { "code": "Tid", "selection": { "filter": "item", "values": [ "2012" ] } } ], "response": { "format": "csv" } }'
data = json.dumps(data)

1 个答案:

答案 0 :(得分:0)

您应该将查询定义为字符串;留下一个Python对象:

data = { "query": [ { "code": "Region", "selection": { "filter": "vs:RegionRiket99", "values": [ "00" ] } }, { "code": "Hustyp", "selection": { "filter": "item", "values": [ "FLERBO", "SMÅHUS" ] } }, { "code": "Tid", "selection": { "filter": "item", "values": [ "2012" ] } } ], "response": { "format": "csv" } }
data = json.dumps(data)

您需要设置application/json请求标头以指明内容是什么。您可以使用urllib.request.Request()对象执行此操作;首先将JSON数据编码为UTF-8:

request = urllib.request.Request(url, data.encode('utf8'))
request.add_header('content-type', 'application/json')
response = urllib.request.urlopen(request)

现在您可以将CSV保存到文件中;使用shutil.copyfileobj()即使对于大型回复也会有效:

import shutil

with open(csvfilename, 'wb') as outf:
    shutil.copyfileobj(response, outf)