A guide on effectively transferring Django lists/dictionaries to JavaScript

Looking to pass a list of items to a JavaScript array, using Django version 2.2.3.

In my views.py:

my_list = ["one", "two"]
    context = {
        'my_list ': json.dumps(my_list),
    }
return render(request, 'my_template.html', context)

In my_template.html:

<script>
var my_array = JSON.parse("{{ my_list|safe }}")
document.write(my_array )
</script>

Although many answers indicate that my code is correct, it does not display any data.

I have also tried:

<script>
var my_string = "{{my_list}}";
var my_array = my_string.split(',');
document.write(my_array)
</script>

When attempting to display the array in this way, I receive:

[" one  "

Answer №2

When working with JSON in JavaScript, it's important to remember that JSON string literals are enclosed in double quotes. To avoid conflicts, you should consider using single quotes around the JSON object instead:

var my_data = JSON.parse('{{ my_list|safe }}')

However, as @NalinDobhal points out in a comment, in most cases you can simply assign the JSON object to a JavaScript variable since JSON is designed to follow the syntax of 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

Converting an Ajax response to a string for comparison with a JavaScript string

How can I convert an Ajax response into a plain text string? I'm storing the Ajax response in a global variable but when I compare it with a JavaScript string, even if they are equal, it returns false. Here is the code snippet: function checkUsn(){ ...

Exploring the connections between Hibernate and AngularJS

I have established a connection between Travelers and Trips in Hibernate: https://i.sstatic.net/YQetP.png To create a new trip for traveler 1, I need to visit the route /frontend/#/trip-creation/1. Here, a form is available: https://i.sstatic.net/BeXnU. ...

Retrieving the 'red' pixel data from the texture rendered with gl.texImage2D

My objective is to transfer a Float32array to my fragment shader using a texture in order to process the data within the shader and then send it back to JavaScript. Since the data is not in the form of an image, I opted to transmit it as 'gl.R32F&apos ...

Is there a way to activate a Superfish jQuery Menu with a click instead of a hover?

After doing some research on the internet, I came across an implementation of Superfish menu by Joel Birch that functions based on onclick instead of hover. I found a link on Github by Karl Swedberg which seems to be what I need. https://gist.github.com/ ...

Issue: An error occurred while trying to parse JSON data in TypeScript due to an undefined 'description' property

Encountering an error message when attempting to retrieve the description attribute from the following Sample Json. Error: TypeError: Cannot read property 'description' of undefined when trying to access json data in typescript import {Age ...

Establishing the request body for RESTful web services utilizing the POST technique

Hey there, I'm currently working on creating a REST response using the POST method. I want to pass variables dynamically instead of hardcoding them. However, I am encountering an issue when trying to send an array as a parameter to the REST web servic ...

Setting a value for a foreign key column

I'm encountering an issue with setting a title for the UserService model, which serves as a foreign key reference to another model. models.py class IndustryService(models.Model): industryname = models.ForeignKey(Industry, on_delete=models.CA ...

What is the best way to incorporate a pristine script into an html webpage using the Python standard library?

Looking to back up my code from the Sololearn site, I want to avoid copy/pasting and instead use a Python script with only the standard library. I've tried various methods like HTMLParser, html.entities, xml.etree, decoding as "utf-8", and using html. ...

The active class in the navbar is malfunctioning in Bootstrap 4

I've been searching high and low to figure out how to add an active class to the current open link in my navbar. I've scoured Google and Stack Overflow for answers, but everything I found only applies to hash-type navbars using href="#". None of ...

Vue 3: How to respond to changes in an object property within an array

I have a Vue 3 application. Within this app, I am aiming to showcase a list of items and provide users with the ability to choose items within the array. The current structure of my component is outlined below: MyComponent.vue <template> <div&g ...

Applying Media Queries Based on Element Height

Situation: In my scenario, there is an image with two buttons below it, all of which share the same width. Issue: When the viewport is too wide horizontally, the buttons are not visible without scrolling down. This poses a challenge for tablets and small ...

The code reached the end of the terminal with a termination error: 1

Looking to leverage the Visual Studio Code IDE ("VSC") for MQL development, rather than relying on the native MetaEditor IDE? Check out this guide for more information: How to code & compile MQL5 in Visual Studio. My query pertains to the compilation ...

How to display a three.js scene in the center of a container

I'm having trouble getting my three.js scene to display above some cards and right below my navigation bar. Currently, the scene is rendering under the cards and is not centered. Despite looking at other forum posts for help, I can't seem to figu ...

How to Manage Specific Types of Promise Rejections in Node.js?

I am exploring Node.JS and I have discovered the usefulness of the unhandledRejection event in capturing unhandled errors. Yet, I am specifically interested in catching a particular type of error. What is the best approach to achieve this selective handl ...

Issue with Jdenticon icons not displaying correctly in ng-repeat loop

Recently, I started using the Jdenticon JavaScript library for generating user icons. This library allows me to input a hash and then render it as either SVG or Canvas. Here is an example code snippet: <svg width="200" height="200" data-jdenticon-has ...

Encountering an AWS Cognito issue while using Angular 4: Error message indicates configuration is missing a

I'm currently in the process of developing a web application that heavily relies on AWS services for its backend infrastructure. As of now, I am utilizing AWS Cognito to manage user sessions within the application. In my development work, I am using A ...

Having trouble getting a Bootstrap 4 select form field to function properly in a Django project

Recently, I delved into the world of Django and decided to incorporate a Bootstrap4 form. To my surprise, when using input fields for text and date, everything worked seamlessly - data was successfully saved in the Django admin panel. However, things took ...

Tips for choosing all elements in a form that have a specific class assigned

I am attempting to target all fields in a form with a specific class name and then select all the remaining fields. This is my form: <form style="margin:20px 0" id="myform_2"> <p> Query Name : <input i ...

Request for a CAC (common access card) in Django

My current setup involves running a Django application on an Apache v2.4.5.2 server. Users are required to input their CAC and PIN when accessing the initial page at www.djangoApp.com. After entering the necessary information, they are directed to the land ...

What is the best way to handle JSON data in Android development?

What is the best way to decode a JSON feed in an Android application? ...