如何将json内容写入csv文件?

时间:2019-04-24 17:25:23

标签: json python-3.x csv

我正在使用api调用来请求数据,该数据返回JSON。我需要将此回复保存到CSV文件。

我能够下拉JSON响应,但是在写入CSV时遇到问题。

# import statements
import json         # package to work with json
import requests     # package to make http requests
import csv

# set global variables
group_id = 0000
api_token = 'yyyy'
api_url = 'https://api.samsara.com/v1'

endpoint_url = api_url + '/fleet/drivers'

# query params for the request
my_params = {"access_token": api_token}

# body data to send with the request
my_data = {"groupId": group_id}

# send POST request to endpoint
resp = requests.post(url = endpoint_url, params = my_params, json = my_data)

# pull out the json
array = resp.json()
text = json.dumps(array)

csvFile = open('/tmp/output.csv','w')
csvwriter = csv.writer(csvFile)
count = 0
for line in text:
    if count == 0:
        header = line.keys()
        csvwriter.writerow(header)
        count += 1
    csvwriter.writerow(line.values())
csvFile.close()

运行上面的代码时,出现以下错误:

  

回溯(最近一次通话最后一次):文件“ get_driver_test4.py”,行   34,在       header = line.keys()AttributeError:“ str”对象没有属性“ keys”

2 个答案:

答案 0 :(得分:1)

将您的问题分解为不同的功能,如下所示:

import json
import requests
import csv

def get_data():
    group_id = 0000
    api_token = 'yyyy'
    api_url = 'https://api.samsara.com/v1'
    endpoint_url = api_url + '/fleet/drivers'

    my_params = {"access_token": api_token}
    my_data = {"groupId": group_id}
    resp = requests.post(url = endpoint_url, params = my_params, json = my_data)
    array = resp.json()
    text = json.dumps(array)

    return text


def write_file(filename, text):
    dataset = json.loads(text)
    drivers = dataset['drivers']

    csvFile = open(filename,'w')
    csvwriter = csv.writer(csvFile)

    # write header
    if len(drivers) > 0:
        keys = drivers[0].keys()
        csvwriter.writerow(keys)

    # write data
    for line in drivers:
       csvwriter.writerow(line.values())

    csvFile.close()

text = get_data()
write_file('output.csv', text)

这样,您可以将您的write_file函数与get_data函数分开测试。

要注意的一件事是0000的GroupID。如果您输入的组ID是这样的,则可能会收到JSON解析错误。如果您确实需要4个字符的数字,请找到一种引用它们的方式,例如"0000"。如果您只对数字感兴趣,请将0000替换为0

要检验您的理论,请在python文件的底部使用类似以下的内容:

text = '{"drivers": [{"id": 134763, "groupId": "0000", "vehicleId": 212014918234742, "currentVehicleId": 212014918234742, "username": "ablah", "name": "Art Blah"}, {"id": 134764, "groupId": "0000", "vehicleId": 212014918234709, "currentVehicleId": 212014918234709, "username": "btodd", "name": "Barry Todd"}]}'
write_file('output.csv', text)

生成的文件

id,groupId,vehicleId,currentVehicleId,username,name
134763,0000,212014918234742,212014918234742,ablah,Art Blah
134764,0000,212014918234709,212014918234709,btodd,Barry Todd

答案 1 :(得分:0)

好吧,这怎么办

const item = objs.slice().reverse().find(obj => obj.action === 'Boot');

您可以调整代码以适合您的需求。

Output.csv

# import statements
import json         # package to work with json
import requests     # package to make http requests
import csv
resp = """
{
    "drivers":[
        {
            "id":134763,
            "groupId":1234,
            "vehicleId":212014918234742,
            "currentVehicleId":212014918234742,
            "username":"ablah",
            "name":"Art Blah"
        },
        {
            "id":134764,
            "groupId":1234,
            "vehicleId":212014918234709,
            "currentVehicleId":212014918234709,
            "username":"btodd",
            "name":"Barry Todd"
        }
    ]
}
"""
text = json.loads(resp)
csvFile = open('output.csv','w')
csvwriter = csv.writer(csvFile, delimiter=',')
line = text["drivers"]
csvwriter.writerow(["id","groupId","vehicleId","currentVehicleId","username","name"])
for l in line:
    csvwriter.writerow([l["id"],l["groupId"],l["vehicleId"],l["currentVehicleId"],l["username"],l["name"]])


csvFile.close()

顺便说一句...

在您提供的示例json中,groupId 0000在python中引发错误,因为它不是有效数字。考虑将0000设为字符串“ 0000”

更多参考...

https://docs.python.org/3/library/csv.html