python API JSON对CSV的响应

vltsax25  于 2022-10-30  发布在  Python
关注(0)|答案(1)|浏览(151)

我正在尝试获取此JSON响应(它只是响应的一个示例)

[
    [
        {
            "session_id": "f02f8b6670a2811b2ee0cfd770a871f6",
            "url": "https://something.bob.com/courses/10546/external_tools/44",
            "context_type": "Course",
            "asset_type": null,
            "controller": "external_tools",
            "action": "show",
            "interaction_seconds": null,
            "created_at": "2021-10-25T02:43:42Z",
            "updated_at": "2021-10-25T02:43:42Z",
            "developer_key_id": null,
            "user_request": null,
            "render_time": 0.223835,
            "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36",
            "asset_user_access_id": 11535927,
            "participated": false,
            "summarized": null,
            "http_method": "get",
            "remote_ip": "184.88.22.85",
            "id": "8e40f170-1225-43c6-8796-9a8ad6f1c351",
            "contributed": false,
            "links": {
                "user": 9526,
                "context": 10546,
                "asset": null,
                "real_user": null,
                "account": 1
            },
            "app_name": null
        },

并将其转换为CSV格式,如下所示

session_id,url,context_type
f02f8b66,google.com,course

等等。
这是我目前掌握的情况

headers = {
       'Authorization': key
}

data_set = []
next_check = 'default'

r = requests.get(domain + "/api/v1/users/9526/page_views?start_time=" + start + "&end_time=" + end + "&per_page=10", headers=headers)
next_ = r.links['next']['url']
d = r.json()
data_set.append(d)

while next_check != 'null':
       r = requests.get(next_, headers=headers)
       next_d = r.json()
       data_set.append(next_d)
       next_check = r.links.get('next', 'null')
       if next_check != 'null':
              next_ = r.links['next']['url']

file = open("requests.json", "w")
file.write(json.dumps(data_set, indent=4))
file.close()

pdObj = pd.read_json("requests.json", orient="index")
print(pdObj)
csvData = pdObj.to_csv('response.csv')

这是我的回应:'list'对象没有属性'values'
我有点迷失在这件事上。我看了Pandas的文档,我认为我做的方式是正确的。

5jvtdoz2

5jvtdoz21#

实际上,这是一个www.example.com的列表json.so,您需要使用panda将此列表转换为csv

df = pd.DataFrame(res)  #this res is the json response

csv_data = df.to_csv(index=False)

相关问题