Reputation: 343
How to merge some data under a single JSON object. As you can see in JSON format below, I want to have (Company address & house address) under the same object (Address).
[
{
"full_data":[
{
"name":"James",
"email":"[email protected]",
"phone":"1234567890",
"address_type":"home"
"address":"address"
}
]
},
{
"full_data":[
{
"name":"James",
"email":"[email protected]",
"phone":"1234567890",
"address_type":"company"
"address":"address"
}
]
}
]
My desired output will be to have the following format:
{
"full_data":[
{
"name":"James",
"email":"[email protected]",
"phone":"1234567890",
"address":{
"house_address":"address",
"company_address":"address"
}
}
]
}
Update:
Here is the code for Views.py file:
class DataView(viewsets.ModelViewSet):
queryset = DataList.objects.all()
serializer_class = DataSerializer
Here is the code for Serializers.py file:
class DataSerializer(serializers.ModelSerializer):
data_details = serializers.SerializerMethodField()
class Meta:
model = DataList
fields = 'data_details'
def get_data_details(self, obj):
return [{
'name': obj.name,
'email': obj.email,
'phone': obj.phone,
'address_type': obj.address_type,
'address': obj.address,
}]
Upvotes: 0
Views: 87
Reputation: 11675
We can do it in python like below
l = [
{
"full_data":[
{
"name":"James",
"email":"[email protected]",
"phone":"1234567890",
"address_type":"home",
"address":"address"
}
]
},
{
"full_data":[
{
"name":"James",
"email":"[email protected]",
"phone":"1234567890",
"address_type":"company",
"address":"address"
}
]
}
]
d = {}
for i in l:
type = i["full_data"][0].pop("address_type")
address = i["full_data"][0].pop("address")
if d.get("full_data"):
d['full_data'][0].update(i['full_data'][0])
d["full_data"][0]["address"][type+"_address"] = address
else:
d.update(i)
d["full_data"][0]["address"] = {type+"_address": address}
print(d)
{'full_data': [{'address': {'company_address': 'address',
'home_address': 'address'},
'email': '[email protected]',
'name': 'James',
'phone': '1234567890'}]}
Upvotes: 1