将JSON对象反规范化为平面对象

时间:2019-06-22 15:15:15

标签: python json pandas ndjson

我有一个json对象,例如

 {
        "id": 3590403096656,
        "title": "Romania Special Zip Hoodie Blue - Version 02 A5",
        "tags": [
            "1ST THE WORLD FOR YOU <3",
            "apparel",
        ],
        "props": [
            {
                "id": 28310659235920,
                "title": "S / romainia All Over Print Full Zip Hoodie for Men (Model H14)",
                "position": 1,
                "product_id": 3590403096656,
                "created_at": "2019-05-22T00:46:19+07:00",
                "updated_at": "2019-05-22T01:03:29+07:00"
            },
            {
                "id": 444444444444,
                "title": "number 2",
                "position": 1,
                "product_id": 3590403096656,
                "created_at": "2019-05-22T00:46:19+07:00",
                "updated_at": "2019-05-22T01:03:29+07:00"
            }
        ]
}

我想将其展平,以便所需的输出看起来像

{"id": 3590403096656,"title": "Romania Special Zip Hoodie Blue - Version 02 A5","tags": ["1ST THE WORLD FOR YOU <3","apparel"],"props.id": 28310659235920,"props.title": "S / romainia All Over Print Full Zip Hoodie for Men (Model H14)","props.position": 1,"props.product_id": 3590403096656,"props.created_at": "2019-05-22T00:46:19+07:00",       "props.updated_at": "2019-05-22T01:03:29+07:00"}
{"id": 3590403096656,"title": "Romania Special Zip Hoodie Blue - Version 02 A5","tags": ["1ST THE WORLD FOR YOU <3","apparel"],"props.id": 444444444444,"props.title": "number 2","props.position": 1,"props.product_id": 3590403096656,"props.created_at": "2019-05-22T00:46:19+07:00","props.updated_at": "2019-05-22T01:03:29+07:00"}

到目前为止,我已经尝试过:

from pandas.io.json import json_normalize
json_normalize(sample_object)

其中sample_object包含json对象,我正在循环浏览这些对象的大文件,并希望将它们以所需的格式展平。

json_normalize不能给我想要的输出,我想保持标签不变,但要展平props并重复父对象信息。

在这方面的任何帮助都将受到赞赏。

2 个答案:

答案 0 :(得分:2)

您想要一些json_normalize的行为,但是要有一个自定义的方式。因此,在部分数据上使用json_normalize或类似数据,然后将其与其余数据组合。

下面的代码更喜欢“或相似的”途径,深入into the pandas codebase以获得nested_to_record辅助函数,该函数使字典扁平化。它用于创建单独的行,这些行将基本数据(所有属性中共有的键/值)与特定于每个props条目的扁平化数据相结合。有一条注释掉的行在没有nested_to_record的情况下执行了等效的操作,但是它有点过分地变平为DataFrame,然后导出为dict

from collections import OrderedDict
import json
import pandas as pd
from pandas.io.json.normalize import nested_to_record

data = json.loads(rawjson)
props = data.pop('props')
rows = []
for prop in props:
    rowdict = OrderedDict(data)
    flattened_prop = nested_to_record({'props': prop})
    # flatteded_prop = json_normalize({'props': prop}).to_dict(orient='records')[0]
    rowdict.update(flattened_prop)
    rows.append(rowdict)

df = pd.DataFrame(rows)

结果:

output data frame

答案 1 :(得分:1)

请尝试以下操作:

import copy

obj =  {
        "id": 3590403096656,
        "title": "Romania Special Zip Hoodie Blue - Version 02 A5",
        "tags": [
            "1ST THE WORLD FOR YOU <3",
            "apparel",
        ],
        "props": [
            {
                "id": 28310659235920,
                "title": "S / romainia All Over Print Full Zip Hoodie for Men (Model H14)",
                "position": 1,
                "product_id": 3590403096656,
                "created_at": "2019-05-22T00:46:19+07:00",
                "updated_at": "2019-05-22T01:03:29+07:00"
            },
            {
                "id": 444444444444,
                "title": "number 2",
                "position": 1,
                "product_id": 3590403096656,
                "created_at": "2019-05-22T00:46:19+07:00",
                "updated_at": "2019-05-22T01:03:29+07:00"
            }
        ]
}

props = obj.pop("props")

for p in props:
    res = copy.deepcopy(obj)
    for k in p:
        res["props."+k] = p[k]
    print(res)

基本上,它使用pop("props")来获取不带"props"的obj(这是在所有结果对象中使用的通用部分),

然后我们遍历道具,并创建包含基础对象的新对象,然后为每个道具中的每个键填充“ props.key”。