如何将 Shopify API json 转换为可读数据框?

How do I convert Shopify API json into a readable dataframe?

我有以下 Python 3.7 代码以 json 格式从 Shopify Admin API 中提取订单数据并将其格式化为 pandas 数据框。

r = requests.get('https://%s:%s@%s.myshopify.com/admin/api/2021-01/orders.json?status=any' % (API_KEY, PASSWORD, SHOP_NAME))
d1 = r.json()

df = pd.json_normalize(d1)
print(df)

目前,我的输出如下所示:

但是,我想要的输出如下所示:

作为参考,d1 如下所示: {'orders': [{'id': 30001, 'email': 'test@gmail.com', 'closed_at': None,...

我是否应该使用 json.normalize() 以外的函数来实现我想要的输出?我也尝试过使用 json.dumps() 在字典和字符串之间进行格式化,但我在那里没有取得任何成功。

所以,其实很简单。您只需要访问 order 键即可从中获取您想要 pd.DataFrame 的值字典。

这是一些示例代码

import pandas as pd
import json

d = {
    'orders': [
        {'id': 3111498449045, 'email': 'test@gmail.com', 'closed_at': None},
        {'id': 3111498449046, 'email': 'test@gmail.com', 'closed_at': None},
        {'id': 3111498449047, 'email': 'test@gmail.com', 'closed_at': None}
    ]
}

pd.DataFrame.from_dict(d['orders'])

要修复您的代码,您应该这样做:

r = requests.get('https://%s:%s@%s.myshopify.com/admin/api/2021-01/orders.json?status=any' % (API_KEY, PASSWORD, SHOP_NAME))
d1 = r.json()

df = pd.DataFrame.from_dict(d['orders'])
print(df)