python - 如何解析对象数组的 JSON 结果并在 Excel 中打印?

标签 python json excel

这是一个由多部分组成的问题。我希望发出请求并在 Excel 中打印结果,标题位于顶部,内容数据位于下面的行中。当我运行以下代码时,我只得到垂直打印的标题,并且不显示任何数据。所以我的问题是: 1.如何获取数据? 2. 如何转换输出,使标题在 Excel 工作表中保持水平(以及下方的数据)?

import requests
import json
import pandas
import xlwt

r = requests.get("https://testapp.deribit.com/api/v2/public/get_trade_volumes?")

db=[]

resp = json.loads(r.text)
for data in resp['result'][0]:
    db.append(data)
for data in resp['result'][1]:
    db.append(data)

df1 = pandas.DataFrame(db)
df1.to_excel('C:/Test/daily_volume.xls')

最佳答案

您的for data in resp并不像您想象的那样工作。

In [26]: db=[] 
    ...:  
    ...: resp = response 
    ...: for data in resp['result'][0]: 
    ...:     db.append(data) 
    ...: for data in resp['result'][1]: 
    ...:     db.append(data) 
    ...:                                                                                                                                                                                                                                       

In [27]: response                                                                                                                                                                                                                              
Out[27]: 
{'jsonrpc': '2.0',
 'result': [{'puts_volume': 1246.1,
   'futures_volume': 1807294.0335,
   'currency_pair': 'btc_usd',
   'calls_volume': 767.4},
  {'puts_volume': 64.0,
   'futures_volume': 130999.2335,
   'currency_pair': 'eth_usd',
   'calls_volume': 79.0}],
 'usIn': 1575569314303219,
 'usOut': 1575569314304869,
 'usDiff': 1650,
 'testnet': True}

In [28]: db                                                                                                                                                                                                                                    
Out[28]: 
['puts_volume',
 'futures_volume',
 'currency_pair',
 'calls_volume',
 'puts_volume',
 'futures_volume',
 'currency_pair',
 'calls_volume']

无论如何,您不必以这种方式循环它。使用给定的 JSON 结构,您可以将其直接传递给 pandas 并获得您想要的内容。

import requests
import pandas as pd

response = requests.get("https://testapp.deribit.com/api/v2/public/get_trade_volumes?").json()
pd.DataFrame(response["result"]).to_excel("daily_volume.xls")

产品

enter image description here

关于python - 如何解析对象数组的 JSON 结果并在 Excel 中打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59200816/

相关文章:

python - 如何在 python 中通过 Soap 发送文件?

python正则表达式: how to remove all punctuation characters from a string but keep those between numbers?

json - 如何在 Jekyll 上使用 pygment JSON 代码?

excel - 将单元格格式化为其他单元格时出现错误 `xlValues` is not defined

将值转换为日期时需要 vba 对象

Python 正则表达式 - 命名组不完全匹配

python - 如何读取所有图像的形状并显示它们,并通过 google colab 显示在数据集文件夹中?

python - 在 webhook 中解析 JSON

IOS如何将JSON字符串保存和加载到内存

excel - 将大型数据集中的字符串转换为数字