如何将JSON转换为CSV

mikeraj2019

我正在尝试将json输出下面的内容转换为csv。

{u'status': u'success', u'data': {u'candles': [[u'2020-05-15T09:15:00+0530', 9163.95, 9165.05, 9090.55, 9115.9, 440475, 7516350], [u'2020-05-15T09:17:00+0530', 9116.25, 9122.5, 9090, 9090.05, 266925, 7550850], [u'2020-05-15T09:19:00+0530', 9090.05, 9095, 9076.6, 9095, 290325, 7609125], [u'2020-05-15T09:21:00+0530', 9094.8, 9095.15, 9082.35, 9092.35, 179925, 7609125], [u'2020-05-15T09:23:00+0530', 9093, 9102.2, 9085, 9097.65, 132450, 7687050], [u'2020-05-15T09:25:00+0530', 9099.7, 9114.8, 9098.3, 9106.85, 165375, 7681425], [u'2020-05-15T09:27:00+0530', 9110.5, 9129.8, 9108.95, 9129.1, 205800, 7681425], [u'2020-05-15T09:29:00+0530', 9127.45, 9142.5, 9119.35, 9138.95, 189525, 7684050], [u'2020-05-15T09:31:00+0530', 9139.95, 9143.15, 9124, 9127, 150975, 7665525], [u'2020-05-15T09:33:00+0530', 9126.9, 9140, 9124, 9138, 101400, 7665525]]}}

我尝试使用以下代码,但输出不期望作为csv

datedata = json_obj3['data']['candles']
encodedUnicode = json.dumps(datedata, ensure_ascii=False).encode('utf-8')
print type(encodedUnicode)

final = encodedUnicode.replace("], [","\n").replace("T"," ").replace("+0530",".000").replace('"','').replace('[[','').replace(']]','').replace('-','.')
print type(final)

所需的输出格式

time,Open,High,Low,Close,Volume
02.09.2019 00:00:00.000,1529.405,1529.505,1528.895,1529.005,71499.9997
02.09.2019 00:03:00.000,1528.932,1529.262,1528.905,1529.185,72030.0004
02.09.2019 00:06:00.000,1529.125,1529.405,1529.015,1529.332,33129.9989
龙鲁特

使用熊猫提供的两个答案是对任务的过大杀伤力,并且没有解决所要求的时间和日期格式。我将使用已经包含的csv软件包:

import csv
from datetime import datetime

data = json_obj3['data']['candles']

with open('out.csv', 'w') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(["time", "Open", "High", "Low", "Close", "Volume"])
    for row in data:
        dt = datetime.strptime(row[0], "%Y-%m-%dT%H:%M:%S%z")
        formatted_dt = dt.strftime("%d.%m.%Y %H:%M:%S.000")
        writer.writerow([formatted_dt] + row[1:])

输出:

time,Open,High,Low,Close,Volume
15.05.2020 09:15:00.000,9163.95,9165.05,9090.55,9115.9,440475,7516350
15.05.2020 09:17:00.000,9116.25,9122.5,9090,9090.05,266925,7550850
...

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章