如果您收到编码响应,您可以使用urllib.unquote
将转义字符替换为其“实际”表示。完成此操作后,您可以使用该json
模块将字符串加载为 Python 对象,然后使用该csv
模块根据响应创建 CSV。您的回复结构将决定您的最终设置方式,但希望这会让您走上正确的道路:
In [1]: import csv
In [2]: import json
In [3]: import urllib
In [4]: json_resp = urllib.quote('[{"name": "John Doe", "age": 35}, {"name": "Jane Doe", "age": 33}]')
In [5]: json_resp # What I believe your response looks like
Out[5]: '%5B%7B%22name%22%3A%20%22John%20Doe%22%2C%20%22age%22%3A%2035%7D%2C%20%7B%22name%22%3A%20%22Jane%20Doe%22%2C%20%22age%22%3A%2033%7D%5D'
In [6]: resp = urllib.unquote(json_resp) #'Unquote' the response
In [7]: resp
Out[7]: '[{"name": "John Doe", "age": 35}, {"name": "Jane Doe", "age": 33}]'
In [8]: content = json.loads(resp) # Turn the resp into a Python object
In [9]: fieldnames = ('name', 'age') # Specify the order in which to write fields
In [10]: with open('mycsv.csv', 'wb') as f:
....: writer = csv.DictWriter(f, fieldnames)
....: writer.writeheader() # Python 2.7+
....: for item in content:
....: writer.writerow(item)
....:
....:
这将编写一个如下所示的 CSV:
name,age
John Doe,35
Jane Doe,33