Exploring the ways to retrieve a serialized JSON object in Django

I am facing an issue accessing the primary key of a Django object serialized in JSON. Here is my JavaScript code:

function makeLink() {
    recorder && recorder.exportWAV(function (blob) {
        let fd = new FormData;
        fd.append("audio", blob);
        let csrftoken = getCookie('csrftoken');
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                var obj = JSON.parse(this.responseText);
                /*console.log(obj[0].pk);*/
                document.getElementById("result").innerHTML = obj.data[0]['pk'];
            }
        }

        xhr.open('POST', uploadAudio_url , true)
        //alert(uploadAudio_url)
        xhr.setRequestHeader("X-CSRFToken", csrftoken);
        xhr.onload = function () {
            // __log("Audio Uploaded to server succesfully");
        };
        xhr.onerror = function (e) {
            // __log("Error Uploading audio" + e)
        };

        xhr.send(fd);
    });

}

I am sending blob data, which represents an audio file, for speech processing on the backend. The backend filters the objects and responds with a queryset in JSON format. I am interested in extracting the primary keys of these objects to display images in a gallery grid.

Below is excerpt from my Views.py:

def process_speech(recognized_audio):
    # Code block omitted for brevity

def upload(request):
    # Code block omitted for brevity

The JSON data received looks like this:

[
    {
     "model": "Galeria.imagen", 
     "pk": 20, 
     "fields": 
                {"image_width": 6000, 
                "image_height": 4000, 
                "fichero_imagen": "files/img/lucas-albuquerque-615558-unsplash.jpg", 
                "keyword": [17, 18]}
    }, 
    {
     "model": "Galeria.imagen", 
     "pk": 21, 
     "fields": 
                {"image_width": 5855, 
                 "image_height": 3860, 
                 "fichero_imagen": "files/img/freestocks-org-794156-unsplash.jpg", 
                 "keyword": [18]}
    }
]

I have attempted different methods to extract the primary key value but ended up with 'undefined' every time.

Your help is appreciated. Thanks in advance.

Answer №1

The main issue at hand is the double serialization of your data into JSON. Initially, you serialize it with

data = serializers.serialize('json', objects)
, and then once more with JsonResponse({'data': data}). By using JsonResponse, the JSON output from the first step gets escaped, transforming the list into a single string.

To resolve this problem, eliminate the embedded JsonResponse and directly pass the JSON.

objects = process_speech(speech)
data = serializers.serialize('json', objects)
return HttpResponse(data)  # Directly pass the JSON to the HttpResponse

After making this change, adjust your JavaScript code to expect the top-level object to be a list without the data attribute:

document.getElementById("result").innerHTML = obj[0]['pk'];

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

Sending User Identification Information to WebChat via WebChat Hooks API

Previously, I had a method for passing the Username and UserID parameters from the URI on Webchat. Here is the code snippet: var queryString = window.location.search; var urlParams = new URLSearchParams(queryString); var user = urlParams.get(&a ...

Using Gson library to handle complex JSON structures in an Android Studio project

My JSON file looks like this: {"code":0,"datas":[{"id":0,"target_id":0},{"id":1,"target_id":0}................]} In my code, I have written the following: // String data; // data contains the JSON data as a string JsonParser jsonParser = new JsonParse ...

Reach the bottom of the page using window.scrollBy

My goal is to create a page that smoothly scrolls continuously, where once it reaches the bottom, it goes back to the top and repeats the scrolling cycle. Currently, I have set up the basic structure of the page. $(document).ready(function() { var scr ...

Transforming jQuery into React - implementing addClass and removeClass methods without using toggle

I'm working on creating two grid resize buttons for a gallery list. One is for a smaller grid (.museum-grid) and the other for a larger grid (.large-grid). Here's what I want to happen when I click #museum-grid-btn: Add class .museu ...

Struggling to locate the earliest date within a nested array of objects

I have an array of objects nested inside another object. My goal is to identify the minimum date from the 'FromDate' property within the 'Market' objects. What would be the most effective method to achieve this when dealing with both si ...

I am struggling to apply custom CSS styles to the scrollbar within a Card component using MUI react

import React from "react"; import Card from "@mui/material/Card"; import CardActions from "@mui/material/CardActions"; import CardContent from "@mui/material/CardContent"; import CardMedia from "@mui/material/Ca ...

Vue modifies the array in the data after creating a duplicate of it

Here is the Vue code snippet I'm working with: export default { name: 'Test', data() { return { test1: ['1', '2', '3'], test2: [{ name: 'Hello' }, { name: &apo ...

Send the JSON data to a remote server in Corona for seamless integration

How can I post data to my server? I am able to fetch data from it but unable to add new data. Below is the code snippet for fetching data: local function networkListener( event ) if ( event.isError ) then print( "Network error!") else local json=e ...

How can you find a matching string within an array?

I am currently working with an array that contains various strings. I need to search for a specific string within the array, but the problem is that the array_search() function only searches for exact matches. Is there a way to find similar strings and ret ...

Loop through various json entries

I have a file containing hundreds of JSON lines. To extract data from each line, I wrote a Python script that currently processes only one line. However, I am now looking for a way to loop through all the lines in the file and extract data from each one. ...

Retrieving JSON information from a nested array

I've noticed that this question has been asked frequently, but I haven't come across a case similar to mine. Here's the array printed out from a JSON response: Array ( [contents] => { "type": "XXXXXXXXXXXXXXX", "previous": " ...

Generating a variety of objects using an array of structures containing distinct random numbers in each

I need assistance in generating distinct arrays of random numbers for each object I create. Currently, all my objects have the same sequence of numbers within their arrays after compiling. Is there a method to generate unique sequences of numbers for e ...

When the mouse is clicked down, make elements move along with the cursor

Is there a way to make picture elements follow the mouse cursor only while the mouse is pressed down? The current script works well but starts following the cursor only after it has been released, which is not the intended behavior. I tried placing the in ...

Exploring the Interplay Between Entity Framework 4.1, MVC3 JsonResult, and Circular References

I am currently delving into Entity Framework Code First development with ASP.NET MVC3. Imagine I have a basic data Model for managing Auctions and Bids, and my goal is to retrieve all the Auctions along with their corresponding Bids. In order to optimize ...

Is it necessary to use JavaScript if jQuery has already been declared?

Is it possible to utilize javascript alongside jquery if jQuery has already been declared in the head section of the webpage? Personally, I believe that javascript is more suitable for specific tasks, while jQuery may be better suited for others. Currently ...

Automatically submit form in Javascript upon detecting a specific string in textarea

Just getting started with JS and I have a question that's been bugging me. I have a simple form set up like this: <form method="POST" action="foo.php"> <textarea name="inputBox123"></textarea> <input type="submit" value="Go" name ...

Categorize an array by their names using Jquery and present them as a list

I have a list of cities and their corresponding countries structured like the following: { "data": [ { "cityname": "Newyork", "countryname": "USA" }, { "cityname": "amsterdam", "countryname": "Netherland" },{ "cityname": "Washington", "country ...

I am currently transferring cross-site forgery tokens through jQuery strings. However, on the subsequent page, I create a fresh token which means their original tokens will no longer align

Alright, so I've been storing the tokens in a session: Session::get('token', 'randomtokenstringhere'); Every time a form is submitted, whether successfully or not, I generate a new token and update their session token. But let&ap ...

AJAX Patch requests in Laravel

My modal is designed to update information related to various countries. // Here is a snippet of the modal HTML code <div id="EditModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div c ...

AngularJS does not bind redefined variables

Having just started delving into Angular, I've encountered an issue while creating an application where a single AngularJS bind fails to update when the value of the bound object changes. This is a simplified version of the app, hence its structure. ...