Utilizing a nested Python list in JavaScript with the help of Django

On my website, I have a feature that displays data in JavaScript Array format, representing a nested list in Python.

To achieve this, I utilize a JavaScript function that retrieves the data from a Django view:

JavaScript function:

var getDataFromFiles1 = function(theUrl) {
    $.ajaxSetup({async: false});
    var xmlHttp = new XMLHttpRequest();
        xmlHttp.open( "GET", theUrl, false );
        xmlHttp.send( null );
        return xmlHttp.responseText;
};

views.py:

a = MyModel.objects.get(c=b, x=y)
json_object = json.dumps(a.data)
return HttpResponse(json_object, content_type="application/javascript")

However, the data that is returned is considered a string by the typeof operator. Trying to use JSON.parse() to convert it into a JavaScript Array does not yield the desired outcome:

var data = getDataFromFiles1(url);
console.log(data + " : " + typeof data)
data = JSON.parse(data)
console.log(data + " : " + typeof data)

The resulting logs show:

"[[\"example\", \"example\", \"example\", \"example\", \"not set\"], [\"example\", \"example\", \"example\", \"example\", \"not set"]]" : string

and

[["example", "example", "example", "example", "not set"], ["example", "example", "example", "example", "not set"]] : string

Is there something obvious that I am overlooking? How can I properly create a JavaScript Array object using this data, without relying on template tags during page load?

Answer №1

Without seeing your specific model, it appears that a.data is likely already in JSON format, meaning you are encoding it twice.

Simply remove the json.dumps function and instead use

HttpResponse(a.data, content_type="application/javascript")
to return the data.

Answer №2

Attempt to re-parse the data using JSON.parse(...). It's possible that the Python script is automatically encoding it to JSON because of

content_type="application/javascript"
.

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

Steps for displaying search results based on state when a button is clicked

My current challenge involves creating a component that displays a list of results upon clicking the "Find" button. However, I am encountering issues with the results state variable not resetting when I utilize setResults([]). In addition, only the most r ...

Using Three.js to seamlessly transition from one Panorama Cube to another with a smooth zoom-in effect

As a newcomer to Three.js, I am currently experimenting with an example featuring a set of 6 image cubes for a panorama effect. This allows users to pan, zoom in, and zoom out around the cubes. If you're interested, you can check out the example here ...

"Learn how to pass around shared state among reducers in React using hooks, all without the need for Redux

I've built a React hooks application in TypeScript that utilizes multiple reducers and the context API. My goal is to maintain a single error state across all reducers which can be managed through the errorReducer. The issue arises when I try to upd ...

Adding an array of objects to a specific key using JavaScript

I'm facing a challenge with adding an array of objects to an existing array of objects using Vue.js. What I'm attempting to accomplish is creating a form repeater within another form repeater. While I was able to successfully implement the first ...

Why does my event dispatch only run once upon form submission in Svelte JS?

My code successfully fetches data and puts it in a card when new data is added to the input. However, the issue arises when more than one data entry is made - although the data gets added to the database, it does not reflect in the data list. Can anyone he ...

Having trouble retrieving the latest value of a scope variable when dealing with multiple partial HTML files controlled by a single Angular controller

In my Angular controller, I have an HTML file that includes two partials. Here is a simplified version: HTML: <!DOCTYPE html> <html> <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> ...

Establishing a variable to serve as a function invocation

Is there a way I can assign a variable to either .prev() or .next()? Here is an example of what I am trying to do: if(x == y) var shift = '.prev()'; else var shift = '.next()'; $("li.active").removeClass('a ...

How can Vue.js leverage dynamic templates within a component?

const CustomComponent = { props: ['index'], template: `<span>I am a custom component: {{ index }}</span>` }; const UserInputResult = { components: { CustomComponent }, props: ['templateString'], template: `& ...

Monitoring changes in session storage with AngularJS

In the sessionStorga, I have stored data from various controllers using a library called https://github.com/fredricrylander/angular-webstorage. The data is being successfully stored and is accessible within the current session. However, I am encountering a ...

Create a conditional statement for handling exceptions on a Unique Constraint

My struggle with Django lies in the absence of a ValidationError due to a missing condition in the UniqueConstraint. Within one of my models, I have established a unique constraint involving a Foreign Key: class Entry(models.Model): """ ...

Selecting HTML5 data attributes using jQuery

There is a button on my page with multiple data attributes, and I am trying to hide it by selecting it based on its class and two specific data attributes. <a href='#' class='wishlist-icon' data-wish-name='product' data-wi ...

Using PHP to identify the origin of a JavaScript file on a webpage

I have been attempting to locate an embedded stream link from a certain webpage. After inspecting the source code of the page, I found the following snippet: <script type='text/javascript'> swidth='640', sheight='460';& ...

Steps for handling errors in Node.js when the query result rowCount is 0 and throwing an error in response

If the rowcount is 0, I need to send a response as failed. If the rowcount is 1, I need to send a success status. Can someone please assist me with this? When I try to print (client.query), it displays the result in JSON format (refer to attached image). ...

When I submit 'name' through Postman, ValidatorExpress notifies me that the input for 'name' is missing

Whenever I use the 'POST' method in Postman with the URL http://localhost:7777/register, and select the options Body and row to paste the object {name: 'Martin}, why does it return "You must supply a name!" from the array ["You must supply a ...

What is the most effective method to escape double quotes in a string when passing it to an external program using PowerShell, especially with a JSON string involved?

Despite reading numerous articles on escaping strings in PowerShell, I have yet to find a satisfactory solution. For example, say I have a file named foo.json that contains a JSON string. My goal is to pass this JSON string as an argument to a program. I ...

What is the reason for needing to refresh when submitting form data in a Node application with an HTTP POST

Code Snippet - Angular .state('studentInfo.newStudent', { url : '/new/student', templateUrl: 'students/new-student.html', controller : function($state, $http){ this.saveStudent = func ...

Why does my body feel devoid whenever I submit a post request from the React JS frontend?

Angular js: export const addUser=( username, email )=> { return (dispatch) => { fetch("http://yourdomain.com/addUser", { method: "post", credentials: 'same-origin', mode: 'no-cors', ...

Visualizing Data with d3.js Radar Charts Featuring Image Labels

After following a tutorial on creating a d3.js radar chart from http://bl.ocks.org/nbremer/21746a9668ffdf6d8242, I attempted to customize it by adding images to the labels. However, I encountered an issue with aligning the images properly. You can view my ...

Troubleshooting MongoDB query criteria in Meteor and JavaScript doesn't yield the expected results

I am encountering an issue with a Products collection that has an attribute called "productCode". My goal is to create a server-side query to fetch a product based on the productCode attribute. Unfortunately, I keep running into a "cannot read property &ap ...

Optimizing Angular's ng-repeat for efficient updates by restricting the watch functionality to the relevant iteration

My task involves creating a table where users can edit certain fields in each row, which will impact other fields within the same row. Due to this requirement, I cannot use bind-once for all the rendered data. To address this issue, I attempted using the ...