json_normalize拆分多个json对象:python

时间:2019-02-07 09:08:40

标签: python json pandas

我有这样的json响应

order_response = {
"orders": [
    {
        "id": '1',
        "email": "b@mail.com",
        "location_id": 9,
        "line_items": [
            {
                "id": 5,
                "product_id": 6,
            }, {
                "id": 7,
                "product_id": 8,
            }
        ]
    }, {
        "id": '2',
        "email": "b@mail.com",
        "location_id": 10,
        "line_items": {
            "id": 3,
            "product_id": 4,
        }
    },
]

}

我想要这样的输出

id email      location_id line_items_id line_items_product_id
1  b@mail.com 9           5             6
1  b@mail.com 9           7             8
1  b@mail.com 10          3             4

我想根据line_items中对象的数量来拆分行。 所以我的方法是使用Pandas的json_normalize功能 如果我在代码中指定了列名,就会出现如下情况。

pd.io.json.json_normalize(report_json, ['line_items'], ['id', 'email'], record_prefix='line_items_')

,但除id, email之外可能还有其他列。我希望这是动态的,即它应该能够处理提供的任何数量的对象而无需显式定义 在这方面的任何帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:2)

首先将列表添加到一个元素字典,然后提取字典的所有键:

    val password = EditText(this)
    password.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
    password.hint = "Password"

L = []
keys = []
for x in report_json['orders']:
    d = {}
    for k, v in x.items():
        if isinstance(v, dict) and k =='line_items':
            d[k] = [v]
        else:
            d[k] = v
        if k !='line_items':
            keys.append(k)
    L.append(d)

print (L)

[
    {
        "id": '1',
        "email": "b@mail.com",
        "location_id": 9,
        "line_items": [
            {
                "id": 5,
                "product_id": 6,
            }, {
                "id": 7,
                "product_id": 8,
            }
        ]
    }, {
        "id": '2',
        "email": "b@mail.com",
        "location_id": 10,
        "line_items": [{
            "id": 3,
            "product_id": 4,
        }]
    }
]