Итак, у меня есть следующий вложенный объект, и я пытаюсь объединить объект на основе ключа specs
. как я могу это исправить.
Введите:
[
{
"person_name": "bob",
"metadata": [
{
"name": "car",
"car_details": [
{
"color": "black",
"type": "bmw",
"specs": [
{
"properties": [
{
"info": [
"sedan",
"germany"
]
},
{
"info": [
"drive",
"expensive"
]
}
]
}
],
"description": "amazing car"
}
]
},
{
"name": "car",
"car_details": [
{
"color": "black",
"type": "bmw",
"specs": [
{
"properties": [
{
"info": [
"powerful",
"convertable"
]
},
{
"info": [
"drive",
"expensive"
]
}
]
}
],
"description": "amazing car"
}
]
}
]
}
]
Ожидаемый результат:
[
{
"person_name": "bob",
"metadata": [
{
"name": "car",
"car_details": [
{
"color": "black",
"type": "bmw",
"specs": [
{
"properties": [
{
"info": [
"powerful",
"convertable"
]
},
{
"info": [
"sedan",
"germany"
]
},
{
"info": [
"drive",
"expensive"
]
}
]
}
],
"description": "amazing car"
}
]
}
]
}
]
пока это код: но он не работает.
from itertools import groupby
import ast, json
headers = ['color', 'type', 'description']
def _key(d):
# get the key from a dictionary
return [d.get(i) for i in headers]
def get_specs(b):
_specs = [c['properties'] for i in b for c in ast.literal_eval(i['specs'])]
return json.dumps([{'specs': [i for b in _specs for i in b]}])
def merge(d):
merged_list = [[a, list(b)] for a, b in groupby(sorted(d, key=_key), key=_key)]
return [{**dict(zip(headers, a)), 'specs': get_specs(b)} for a, b in merged_list]