简体   繁体   English

根据属性展平JSON-python

[英]Flatten JSON based on an attribute - python

I have a json array like this: 我有一个像这样的json数组:

[
    {
        '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: 我想在字段values上展平此数组,例如:

[
    {
        '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? 在python中最有效的方法是什么?

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)

Your JSON is not technically valid, but assuming it is and that is iterable as a list : 您的JSON在技术上无效,但假设它是有效的,并且可以作为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"}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM