Having trouble transforming an HTTP response into JSON format?

Utilizing my own API, I am fetching data using the following code:

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 is retrieved from this function and is accessible 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')

This section provides information on the corresponding 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()

When converting the data to JSON format, it unexpectedly results in a string representation

Type of data: string 
Type of features: undefined 
No features found in the JSON data.

I am facing challenges in comprehending why this occurs. Specifically, I aim to extract the coordinates attributes utilizing Json, but the current output impedes this process.

Answer №1

During this stage, the response body is transformed into a JavaScript object:

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

However, in the next phase, the process reverses itself, and you end up with a JSON string once again.

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

It's important to note that since a string does not have a .features property, trying to access data.features doesn't make sense because data is a string.

If you eliminate this line, the logic becomes clearer:

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

Answer №2

The answer came in the form of replacing

return HttpResponse(json.dumps(peak_data), content_type='application/json')

With a conventional HTTP response.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to dynamically adjust the select option?

I need help with handling JSON objects: [ { id: "IYQss7JM8LS4lXHV6twn", address: "US", orderStatus: "On the way", }, ]; My goal is to create a select option for the order status. If the current status is "On ...

What is the process of deserializing JSON data?

Although this question has been raised multiple times, I am still struggling to fix it. So here is my own take on the issue. I encounter this JSON data: [{"madde_id":"71690","kac":"0","kelime_no":"908 ...

Sending multiple HTTP requests sequentially

I've been attempting to send a request object to a server repeatedly in a loop, aiming to execute the task 1000 times. The scenario is reminiscent of the movie Office Space, where a small sum is extracted from numerous bank accounts. Here's the ...

Struggling to refine the result set using jsonpath-plus

Utilizing the jsonpath-plus module (typescript), I am currently working on navigating to a specific object within a json document. The target object is nested several levels deep, requiring passage through 2 levels of arrays. When using the following jsonp ...

Uploading a file with AngularJS and storing it in a database

I have been attempting to implement ngFileUpload in order to upload images and store them in a database – specifically, a mongoLab database that accepts JSON objects which can be posted using this syntax: $http.post('myMongoName/myDb/myCollection/ ...

Retrieving a boolean value (from a JSON file) to display as a checkbox using a script

Currently, I am utilizing a script to fetch data from a Google Sheet $.getJSON("https://spreadsheets.google.com/feeds/list/1nPL4wFITrwgz2_alxLnO9VBhJQ7QHuif9nFXurgdSUk/1/public/values?alt=json", function(data) { var sheetData = data.feed.entry; va ...

How to Display Prices in Euros Currency with Angular Filter

Can someone help me figure out how to display a price in euros without any fractions and with a dot every 3 digits? For example, I want the price 12350.30 to be shown as 12.350 €. I attempted to use the currency filter but it only worked for USD. Then ...

How can JavaScript be used to deactivate an HTML form element?

Within this form, there are two selection buttons that require client-side validation. The user must choose one of them, and once a selection is made, the other button should automatically be disabled. Below is the script I have implemented: <html> ...

Error message: The 'event' variable is not defined in the Firebase function

I am in the process of creating an appointment application which includes a notification feature. I have integrated Firebase functions to send notifications to users when a new appointment is booked or canceled. However, I encountered an error that says Re ...

The function crypto.randomUUID() does not exist in the Vitest library

vite.config.ts import { sveltekit } from '@sveltejs/kit/vite'; const config = { plugins: [sveltekit()], test: { include: ['**/*.spec.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'], environment: 'jsdom', glo ...

Modify the class of a div element depending on the value of a data attribute

I am faced with a situation where I have an iframe and two different sets of CSS codes - one for landscape orientation and one for portrait orientation. However, these are not specifically for the device's orientation but rather for the content loaded ...

What could be causing the error when attempting to release this Node-MySQL pool?

My first attempt at utilizing connection pooling is with Node.js. I crafted a database connection module in Node.js to establish a single connection, which is then referenced within a pooling function for later use when passed to different modules. /* D ...

Preventing dragging in Vis.js nodes after a double click: a definitive guide

Working with my Vis.js network, I have set up an event listener to capture double clicks on a node. ISSUE: After double-clicking a node, it unexpectedly starts dragging and remains attached to the mouse cursor until clicked again. How can I prevent this b ...

Utilizing jQuery to dynamically add classes

I am looking to dynamically add a date picker to input fields using jquery. It seems to be working fine for the first text field, but as soon as I add additional fields, it stops working. Any suggestions on how I can fix this? Thank you in advance. <ta ...

Can anyone guide me on creating a Mapbox map layer using React.js?

I'm currently in the process of creating a polygon layer on top of my Mapbox map using ReactMapboxGL. I have some Mapbox Javascript code that I need to convert into React.js format: map.on('load', function () { map.addLayer({ ...

Using the jQuery library to write information to a .json file using the getJSON method

Can user input data be saved in a one-way stream or is it possible to do so using other methods? I have not been able to find any documentation on this, and if not, what alternatives are there for saving user input data without the need for a full databa ...

Managing simultaneous asynchronous updates to the local state

There is a scenario where a series of asynchronous calls are made that read from a local state S, perform certain computations based on its current value, and return an updated value of the local state S'. All these operations occur at runtime, with ...

There seems to be an issue with the loading of the JSON file

I have created a JSON representation that I would like to visualize using D3JS as a treemap. Following this tutorial: https://bl.ocks.org/d3indepth/d4f8938a1fd0914b41ea7cb4e2480ca8 The JSON I generated from the data is displaying correctly in the treemap ...

When data is submitted through the POST method, it mysteriously disappears

When I send the "user" variable to another page called Survey.php, here's how it looks: In the index.html file: <form action="Survey.php" method="post" name="frm"> <div><input type="text" name= ...

Converting CSDL format into JSON data structure

Is there a way to convert data retrieved in CSDL format from an Oracle DB into JSON format using NODE JS? export async function getRecepFarma(req: Request, res: Response): Promise<Response> { const conn = await connect(); const result = await ...