将JSON转换为.csv [英] Converting JSON to .csv

查看:136
本文介绍了将JSON转换为.csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现有人将某些数据下载到JSON文件中(我认为!-我是新手!).该文件包含有关近600名足球运动员的数据.

I've found some data that someone is downloading into a JSON file (I think! - I'm a newb!). The file contains data on nearly 600 football players.

这里是文件: https://raw.githubusercontent. com/llimllib/fantasypl_stats/f944410c21f90e7c5897cd60ecca5dc72b5ab619/data/players.1426687570.json

是否可以获取某些数据并将其转换为.csv?具体是固定记录"?

Is there a way I can grab some of the data and convert it to .csv? Specifically the 'Fixture History'?

在此先感谢您的帮助:)

Thanks in advance for any help :)

推荐答案

Python为此提供了一些不错的库.如果将以下代码复制到文件中并另存为 fix_hist.py 或其他内容,然后将JSON文件另存为 file.json 在同一目录中,它将创建一个包含夹具历史记录的csv文件,每个都保存为一行.只需在命令提示符下运行python fix_hist.py(或Mac终端):

Python has some good libraries for doing this. If you copy the following code into a file and save it as fix_hist.py or something, then save your JSON file as file.json in the same directory, it will create a csv file with the fixture histories each saved as a row. Just run python fix_hist.py in your command prompt (or terminal for mac):

import csv
import json

json_data = open("file.json")
data = json.load(json_data)

f = csv.writer(open("fix_hists.csv","wb+"))

for i in data:
    fh = data[i]["fixture_history"]
    array = fh["all"]
    for j in array:
        f.writerow(j)

json_data.close()

要将其他数据添加到灯具历史记录,可以在写入行之前添加插入语句:

To add additional data to the fixture history, you can add insert statements before writing the rows:

import csv
import json

json_data = open("file.json")
data = json.load(json_data)

f = csv.writer(open("fix_hists.csv","wb+"))

arr = []

for i in data:
    fh = data[i]["fixture_history"]
    array = fh["all"]
    for j in array:

        try:
            j.insert(0,str(data[i]["first_name"]))
        except:
            j.insert(0,'error')

        try:
            j.insert(1,data[i]["web_name"])
        except:
            j.insert(1,'error')

        try:
            f.writerow(j)
        except:
            f.writerow(['error','error'])

json_data.close()

使用insert(),只需指出您希望数据点作为第一个参数在行中的位置即可.

With insert(), just indicate the position in the row you want the data point to occupy as the first argument.

这篇关于将JSON转换为.csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆