根据属性展平JSON-python [英] Flatten JSON based on an attribute - python

查看:206
本文介绍了根据属性展平JSON-python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的json数组:

I have a json array like this:

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

我想在字段values上将此数组展平,使得:

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'
    }
]

在python中最有效的方法是什么?

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

推荐答案

您的JSON从技术上讲不是有效的,但假设它是有效的,并且可以作为list进行迭代:

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)

结果:

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

这篇关于根据属性展平JSON-python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆