问题
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