【问题标题】:API JSON Response to CSV对 CSV 的 API JSON 响应
【发布时间】:2022-11-10 08:15:26
【问题描述】:

我正在尝试获取这个 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')

这是我的回应: “列表”对象没有属性“值”

我有点迷失了这个。我查看了 Pandas 文档,我认为我的做法是正确的。

【问题讨论】:

    标签: python python-3.x pandas csv


    【解决方案1】:

    实际上这是一个 json 列表。所以您需要使用 pandas 将此列表转换为 csv

    df = pd.DataFrame(res) #这个res是json响应

    csv_data = df.to_csv(index=False)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-19
      • 2019-02-21
      • 2021-08-17
      • 2017-07-02
      相关资源
      最近更新 更多