2

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?

Darth.Vader
  • 5,079
  • 7
  • 50
  • 90

2 Answers2

0
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)
GuangshengZuo
  • 4,447
  • 21
  • 27
0

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"}]
JacobIRR
  • 8,545
  • 8
  • 39
  • 68