[英]Adding scrip to export python result from json to excel or csv file
I am new to the Python world so apologies.我是 Python 世界的新手,所以很抱歉。 I am looking into a set of time series I have downloaded from an API.
我正在研究从 API 下载的一组时间序列。 These data have been printed as JSON file (as seen in the below code).
这些数据已打印为 JSON 文件(如下面的代码所示)。 However, how can I convert this data from JSON to EXCEL or CSV?
但是,如何将此数据从 JSON 转换为 EXCEL 或 CSV?
Below is what I used:以下是我使用的:
import requests
payload = "{\"startDate\": 20190930, \"endDate\": 20191018, \"tags\":[\"PAYMENT.REIMBURSEMENT.1Y.BLOOMBERG\"]}"
headers = {
'content-type': "application/json",
'accept': "application/json",
'authorization': "Bearer AAIkOWNmNGVjMzctYTg5MC00YjhiLWE4MTEtNmE4ZDUzMzU1OWVlGUDsir"
}
proxyDict = {"http": "http://webproxy.payment.nsroot.net:8080/", "https": "http://payment.nsroot.net:8080/"}
r = requests.post(url="https://payment.com/data?client_id=9cf4ec37-a890-4b8b-a811-6a8d533559ee", data=payload, headers=headers, proxies=proxyDict)
print(r.json())
Below is the result that the above code is providing.以下是上述代码提供的结果。
{'frequency': 'DAILY', 'body': {'PAYMENT.REIMBURSEMENT.1Y.BLOOMBERG': {'x': [20190930, 20191001, 20191002, 20191003, 20191004, 20191007, 20191008, 20191009, 20191010, 20191011, 20191014, 20191015, 20191016, 20191017, 20191018], 'c':[ [60.0392, 60.0391, 60.0391, 60.0391, 60.0391, 60.0391, 60.0391, 60.0391, 60.0391, 60.0391, 60.0391, 60.039, 60.039, 60.039, 60.039]][1], 'type': 'SERIES'}}, 'status': 'OK'} {'频率':'每日','正文':{'PAYMENT.REIMBURSEMENT.1Y.BLOOMBERG':{'x':[20190930, 20191001, 20191002, 20191003, 20191004, 20191007, 20191008, 010191009, 20191009, 20191009, 2 20191014、20191015、20191016、20191017、20191018],'c':[[60.0392、60.0391、60.0391、60.0391、60.0391、60.0391、60.0391、60.0391、60.0391 ],“类型”:“系列”}},“状态”:“确定”}
Can you let me know how to convert that to csv file?您能告诉我如何将其转换为 csv 文件吗? Where Column A is the Date in (yyyymmdd) and Column B are the Values like the below >
其中 A 列是 (yyyymmdd) 中的日期,B 列是如下值>
Dates Values 20190930 60.0392... ... 20191018 60.039日期值20190930 60.0392... ... 20191018 60.039
Thank you.谢谢你。
result = list(zip(test['body']['PAYMENT.REIMBURSEMENT.1Y.BLOOMBERG']['x'], test['body']['PAYMENT.REIMBURSEMENT.1Y.BLOOMBERG']['c']))
import csv
with open('PAYMENT.REIMBURSEMENT.1Y.BLOOMBERG', 'w', newline='') as csvfile:
fieldnames = ['Date', 'values']
writer = csv.writer(csvfile, delimiter=',',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
writer.writerow(fieldnames)
for row in result:
writer.writerow(row)
if you need to convert to excel with sheet name following is the code.如果您需要转换为 excel 的表名称,则代码如下。
import pandas as pd
df = pd.DataFrame(result, columns=['Date', 'values'])
df.to_excel('file.xlsx', sheet_name='PAYMENT.REIMBURSEMENT.1Y.BLOOMBERG', index=False)
First create a path to you desktop, and put it in a constant (conventionally noted in UPPER_CASE):首先为您的桌面创建一个路径,并将其放入一个常量中(通常在 UPPER_CASE 中注明):
import pathlib
DESKTOP_PATH = pathlib.Path('/Users/user_name/Desktop')
Iterate over the key and values in you json's body, as per your request, the key is used as the file name, which is why it is held in a variable by that name, and the values are the dictionary holding the csv data:遍历 json 正文中的键和值,根据您的请求,键用作文件名,这就是为什么它以该名称保存在变量中的原因,值是保存 csv 数据的字典:
for file_name, data in r.json()['body']:
csv_rows = '\n'.join(','.join(values) for values in zip(*data.values()))
(DESKTOP_PATH / filename).write_text(f'{",".join(data.keys())}\n{csv_rows}')
Inside the for loop, we build the csv corresponding to each file: zip(*data.values())
converts the values list, which holds a list of lists in the form of [column_a_values, column_b_values, ...]
, to an iterator which combines all the elements on the same row.在 for 循环中,我们构建了与每个文件对应的 csv:
zip(*data.values())
将保存[column_a_values, column_b_values, ...]
形式的列表列表的值列表转换为迭代器,它将同一行上的所有元素组合在一起。 ie list(zip(*[[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
equals [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
.即
list(zip(*[[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
等于[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
。
We then join all the values in a row by with a comma by using ','.join(values)
and join the rows with new lines between them by using '\n'.join(...)
.然后,我们使用
','.join(values)
用逗号将一行中的所有值连接起来,并使用'\n'.join(...)
将行与它们之间的新行连接起来。
Finally, we write all that text in one go using write_text on a concatenation of the desktop path and the filename given by DESKTOP_PATH / filename
, and the final text is given by f'{",".join(data.keys())}\n{csv_rows}'
which first outputs the column names, and then the rows we have calculated above.最后,我们在一个 go 中使用 write_text 将所有文本写入桌面路径和
DESKTOP_PATH / filename
给出的文件名的串联,最终文本由f'{",".join(data.keys())}\n{csv_rows}'
首先输出列名,然后是我们上面计算的行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.