【问题标题】:Flatten JSON response and output to csv展平 JSON 响应并输出到 csv
【发布时间】:2021-12-27 22:30:53
【问题描述】:

我似乎已经用尽了互联网搜索感觉很常见的事情,我需要一些帮助。

我正在使用 requests 库进行 API 调用,每次调用返回一个 JSON 响应 - 我将循环并进行多次调用。

我想将来自许多 API 调用的所有响应组合到一个 python 数据结构中,然后将结果导出到 CSV。

一个 API 响应如下所示:

{
    "status": "1",
    "msg": "Success",
    "data": {
      "id": "12345",
      "PriceDetail": [
        {
          "item": "Apple",
          "amount": "10",
          "weight": "225",
          "price": "92",
          "bestbeforeendeate": "30/09/2023"
        }
        ]
    }
}

我的最终输出应该是一个 CSV 文件,在随后的行中包含以下标题和数据:

id item amount weight price bestbeforeendeate
12345 apple 10 225 92 30/09/2023
..... ..... .. ... .. ..........

我已经查看了将响应组合到字典中,命名为元组,数据框,并尝试了从 dictwriter、csvwriter、normalize 等所述结构中导出的各种选项。不过,我仍在努力使其中的任何一个工作.

我得到的最接近的是(我将结果保存到 JSON 文件以停止访问 API):

with open('item.json') as json_file: 
    data_set = json.load(json_file) 
    for data in data_set: 
        if data['msg'] == 'Success': 
            id = data['data']['id'] 
            return_data[id] = data['data']['PriceDetail'] 

df = pd.json_normalize(data['data']['PriceDetail']) 
print(df) 

我无法将 id 添加到数据框

任何建议将不胜感激。

谢谢,

【问题讨论】:

  • “告诉我如何解决这个编码问题”是off-topic for Stack Overflow。我们希望您发送honest attempt at the solution,发布该尝试,然后询问有关它的具体问题(即解释它为什么不起作用或它有什么问题)。
  • 我尝试了几种解决方案;我很高兴在此处发布其中的一些内容或针对新问题发布?
  • 我建议发布看起来最有希望的一篇,或者如果它们不太长的话,可以发布几篇。无论如何,请务必指出每个问题的问题。
  • 我得到的最接近的是:(我将结果保存到 JSON 文件以停止访问 API)使用 open('item.json') 作为 json_file: data_set = json.load(json_file)对于 data_set 中的数据: if data['msg'] == 'Success': id = data['data']['id'] return_data[id] = data['data']['PriceDetail'] df = pd .json_normalize(data['data']['PriceDetail']) print(df) 我无法将 id 添加到其中
  • 请在您的问题中输入信息,尤其是代码。

标签: python json pandas python-requests export-to-csv


【解决方案1】:

Pandas 有一个叫做json_normalize 的函数,它可以直接将一个dict 转换成一个dataframe。要将 JSON 字符串转换为 dict,您可以简单地使用 json 库。 我找到的好的来源是this`。

import json
import pandas as pd

# Test string, assuming it is from API
test_string = """{
    "status": "1",
    "msg": "Success",
    "data": {
      "id": "12345",
      "PriceDetail": [
        {
          "item": "Apple",
          "amount": "10",
          "weight": "225",
          "price": "92",
          "bestbeforeendeate": "30/09/2023"
        }
        ]
    }
}"""

# Function converts the api result to the dataframe and appends it to df
def add_new_entry_to_dataframe(df, api_result_string):
    input_parsed = json.loads(api_result_string)
    df_with_new_data = pd.json_normalize(input_parsed['data']['PriceDetail'])
    df = df.append(df_with_new_data)
    return df
    

# The dataframe you want to store everything
df = pd.DataFrame()

## Loop where you fetch new data
for i in range(10):
    newly_fetched_result = test_string
    df = add_new_entry_to_dataframe(df, newly_fetched_result)


df = df.reset_index()

# Save as .csv
df.to_csv('output.csv')

print(df)

以上代码的输出:

item amount weight price bestbeforeendeate
0  Apple     10    225    92        30/09/2023
0  Apple     10    225    92        30/09/2023
0  Apple     10    225    92        30/09/2023
0  Apple     10    225    92        30/09/2023
0  Apple     10    225    92        30/09/2023
0  Apple     10    225    92        30/09/2023
0  Apple     10    225    92        30/09/2023
0  Apple     10    225    92        30/09/2023
0  Apple     10    225    92        30/09/2023
0  Apple     10    225    92        30/09/2023

编辑:我重新审视了这个问题,并认为我分享了另一个解决方案,这可能对你更好。下面的代码不是随着时间的推移构建一个巨大的数据框,而是将获取的数据直接附加到 CSV 文件中。好处是,如果程序崩溃或您终止它,所有数据都已经在 CSV 中。

# Function converts the json string to a dataframe and appends it directly to the CSV file
def add_json_string_to_csv(api_result_string):
    input_parsed = json.loads(api_result_string)
    df_with_new_data = pd.json_normalize(input_parsed['data']['PriceDetail'])
    df_with_new_data.to_csv('output.csv', mode='a', header=False)

## Loop where you fetch new data
while (True):
    newly_fetched_result = test_string
    add_json_string_to_csv(newly_fetched_result)

【讨论】:

  • 谢谢,@JANO,我还需要包含 id,所以在这个例子中,12345 值?
  • 您可以使用参数 meta 从您提供的链接中指定数据框中的元数据列表 - 它确实有效!谢谢
  • 不客气!很高兴我能帮助你。如果您有兴趣,我还添加了另一个解决方案。
猜你喜欢
  • 2020-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-03
  • 1970-01-01
相关资源
最近更新 更多