2017-09-02 4 views
2

J'ai un tableau JSON comme ceci:Aplatir JSON basé sur un attribut - python

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

Je veux aplatir ce tableau sur le terrain values tel que:

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

Quel est le plus moyen efficace de le faire en python?

Répondre

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) 
0

Votre JSON est pas techniquement valable, mais en supposant qu'il est et qui est itérables comme 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) 

Résultat:

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