【发布时间】:2017-03-22 08:24:23
【问题描述】:
我正在从 API 中提取信息。返回的数据为 JSON 格式。我必须遍历并为多个输入获取相同的数据。我想将每个输入的 JSON 数据保存在 python 字典中以便于访问。这是我目前所拥有的:
import pandas
import requests
ddict = {}
read_input = pandas.read_csv('input.csv')
for d in read_input.values:
print(d)
url = "https://api.xyz.com/v11/api.json?KEY=123&LOOKUP={}".format(d)
response = requests.get(url)
data = response.json()
ddict[d] = data
df = pandas.DataFrame.from_dict(ddict, orient='index')
with pandas.ExcelWriter('output.xlsx') as w:
df.to_excel(w, 'output')
使用上面的代码,我得到以下输出:
a.com
我还获得了仅包含第一行数据的 excel 输出。我的输入 csv 文件有接近 400 行,所以我应该在输出和输出 excel 文件中看到超过 1 行。
如果您有更好的方法来做到这一点,那将不胜感激。此外,我得到的 excel 输出很难理解。我想使用字典和子字典读取 JSON 数据,但我不完全理解底层数据的格式 - 我认为它看起来最接近 JSON 数组。
我查看了许多其他帖子,包括 Parsing values from a JSON file using Python? 和 How do I write JSON data to a file in Python? 和 Converting JSON String to Dictionary Not List 和 How do I save results of a "for" loop into a single variable?,但到目前为止,这些技术都没有奏效。如果可能的话,我宁愿不要腌制。
我是 Python 新手,因此感谢您提供任何帮助!
【问题讨论】:
标签: python json loops dictionary