Flatten JSON based on an attribute - python

ε祈祈猫儿з 提交于 2019-12-24 05:46:35

问题


I have a json array like this:

[
    {
        'id': 1,
        'values': [
            {
                'cat_key': 'ck1'
            },
            {
                'cat_key': 'ck2'
            }
        ]
    },
    {
        'id': 2,
        'values': [
            {
                'cat_key': ck3
            }
        ]
    }
]

I want to flatten this array on the field values such that:

[
    {
        'id': 1,
        'cat_key': 'ck1'
    },
    {
        'id': 1,
        'cat_key': 'ck2'
    },
    {
        'id': 2,
        'cat_key': 'ck3'
    }
]

What is the most efficient way to do this in python?


回答1:


obj = json.loads(json_array)
new_obj = [] 
for d in obj:
    if d.get('values'):
        for value in d['values']:
            new_obj.append(dict(id=d['id'],cat_key=value['cat_key']))
new_json = json.dumps(new_obj)



回答2:


Your JSON is not technically valid, but assuming it is and that is iterable as a list:

out = []
for d in your_json:
    for v in d.get('values', []):
        out.append({'id': d['id'], 'cat_key': v['cat_key']})
print json.dumps(out)

Result:

[{"id": 1, "cat_key": "ck1"}, {"id": 1, "cat_key": "ck2"}, {"id": 2, "cat_key": "ck3"}]


来源:https://stackoverflow.com/questions/46010220/flatten-json-based-on-an-attribute-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!