skip to Main Content

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


  1. Chosen as BEST ANSWER

    The solution was to replace

    return JsonResponse(peak_data, safe=False, content_type='application/json')
    

    By a standart HTTP response.


  2. In this step you turn your response body into a javascript object:

          .then(response => response.json()) 
    

    In this step you do the opposite again, so you’re back to a JSON string.

          .then(response => JSON.stringify((response))) 
    

    A string will not have a .features property, so data.features makes no sense because data is a string.

    If you remove this line it makes more sense:

          .then(response => JSON.stringify((response))) 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search