I’m fetching my own API,
fetch('/guidebook/api/peak-data/')
.then(response => response.json())
.then(response => JSON.stringify((response)))
.then(data => {
console.log('Raw JSON data:', data);
console.log('Type of data:', typeof data);
console.log('Type of features:', typeof data.features);
})
.catch(error => {
console.log('Error:', error);
});
The data come from this function, it’s published in api/peak-data
urlpatterns = [
path('', views.returnPage),
path('api/peak-data/', views.get_peak_data, name='peak_data'),
]
def get_peak_data(request):
peaks = Peak.objects.all()
peak_data = serialize('geojson', peaks, geometry_field='peak_coordinates')
return JsonResponse(peak_data, safe=False, content_type='application/json')
Here is the associated django model :
class Peak(models.Model):
peak_id = models.BigIntegerField()
peak_name = models.CharField(max_length=80)
peak_coordinates = postgismodel.PointField(geography=True, default=Point(0, 0), blank=True, null = True)
peak_elevation = models.IntegerField()
I Convert it to JSON, and for some reason, I obtain a string
Type of data: string
Type of features: undefined
No features found in the JSON data.
I’m struggling to understand why. In particular, I’d like to isolate the coordinates attributes using the Json, but since I do not have one, I can’t
2
Answers
The solution was to replace
By a standart HTTP response.
In this step you turn your response body into a javascript object:
In this step you do the opposite again, so you’re back to a JSON string.
A string will not have a
.features
property, sodata.features
makes no sense becausedata
is a string.If you remove this line it makes more sense: