I’ve a list of dictionaries and want to get rid of the external list array. Take into consideration the array below,
JavaScript
x
19
19
1
[
2
{
3
"stores": [
4
{
5
"id": 1,
6
"storeName": "Green Mart",
7
"lat": 12.905616,
8
"lon": 77.610101,
9
"offer": [
10
{
11
"offer": "Get 10% OFF on Fruits & Vegetables"
12
}
13
]
14
},
15
16
]
17
}
18
]
19
My serializer looks like,
JavaScript
1
17
17
1
class storesSerializer(serializers.ModelSerializer):
2
offer = StoreOffersSerializer(read_only=True, many=True)
3
storeName = serializers.CharField(source="store_name")
4
lat = serializers.FloatField(source="latitude")
5
lon = serializers.FloatField(source="longitude")
6
7
class Meta:
8
model = Vendors
9
fields = ('id', 'storeName', 'lat', 'lon', 'offer')
10
11
class CategoryStoreSerializer(serializers.ModelSerializer):
12
stores = storesSerializer(read_only=True, many=True)
13
14
class Meta:
15
model = CategoryStore
16
fields = ('stores',)
17
and the view definition is,
JavaScript
1
5
1
if request.method == 'POST':
2
c = CategoryStore.objects.filter(category=request.data['cat_id'])
3
serializer = CategoryStoreSerializer(c, many=True)
4
return Response(serializer.data)
5
Advertisement
Answer
You can use the index of list to refer to the inner dictionary and omit the outer bracket.
JavaScript
1
19
19
1
a = [
2
{
3
"stores": [
4
{
5
"id": 1,
6
"storeName": "Green Mart",
7
"lat": 12.905616,
8
"lon": 77.610101,
9
"offer": [
10
{
11
"offer": "Get 10% OFF on Fruits & Vegetables"
12
}
13
]
14
},
15
16
]
17
}
18
]
19
The below is the output of a[0]:
JavaScript
1
18
18
1
{
2
"stores": [
3
{
4
"id": 1,
5
"storeName": "Green Mart",
6
"lat": 12.905616,
7
"lon": 77.610101,
8
"offer": [
9
{
10
"offer": "Get 10% OFF on Fruits & Vegetables"
11
}
12
]
13
},
14
15
]
16
}
17
18