Issue encountered while attempting to parse JSON data

I've been dealing with JSON data in Django view and parsing it in JavaScript to extract the necessary information.

This is a snippet from my view.py file (Django)

ibms = []
for i in range(2, 5):
    ibm = Mapa(i, wsMapa)
    ibms.append(ibm.__dict__)
ibms = json.dumps(ibms)

return render(request, 'mapas/index.html', {'ibms': ibms})

The output of the ibm variable in the Django template is:

[{"numeroIbm": "AUTO P"}, {"numeroIbm": "PTB"}, {"numeroIbm": "FAROL"}]

This is part of my index.html file (JS code embedded)

{{ ibms|json_script:"ibms" }}
<script>
    const mydata = JSON.parse(document.getElementById("ibms").textContent);
    const mydata2 = JSON.parse(mydata);
</script>

The issue I'm facing is that I have to use JSON.parse twice to obtain the JavaScript object. The variable mydata, despite being parsed, remains in string format. The desired result is achieved only after the second parsing (mydata2).

Could someone please explain what might be causing this?

Thanks in advance!

Answer №1

A better approach is to avoid dumping it directly into the view, like this:

data = [Mapa(item, wsMapa).__dict__ for item in range(2, 5)]

return render(request, 'mapas/index.html', {'data': data})

Then, you can process it in the following way:

{{ data|json_script:"data" }}
<script>
    const myInfo = JSON.parse(document.getElementById("data").textContent);
    // no need for a second parsing step
</script>

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

Vue3 - Implementing a seamless communication channel between two child components

Vue 3 has brought about changes in my component structure, as shown below: https://i.sstatic.net/bgtPB.png In this setup, ChildA can communicate with ChildB and requires ChildB to update its state accordingly. In Vue 2, I could send an event from ChildA: ...

Display the information from a JSON array using an alert box

Similar Question: How can I access a specific value in a nested data structure or JSON? I am trying to display data from a JSON array using the following code, but it is not working: var Content = [{ "01":[{"text":"blablablablabla","foo":"abeille ...

Retrieve every potential option of a dropdown menu

One of my tasks involves working with a select field that has various values: africa europe america asia oceania Whenever a value is selected, I aim to apply a specific CSS class to a particular div, with the name of the CSS class matching the selected v ...

Activate a function upon the clicking of a button by utilizing a directive in Angular.js

In my directive, there is a function called "myFunction()", and in the template, I have a button. When the button is clicked, I want to execute the function without using ng-click for specific reasons. Instead, I am looking to assign a class to the button ...

Publishing a NodeJS + Express + MySQL application on Heroku involves deploying the server side only, excluding the React frontend

I have a React + NodeJS + Express + MySQL project that we're trying to deploy on Heroku. It's set to auto deploy whenever something is pushed to the master branch of GitHub. The problem we're facing is that while the server routes are deplo ...

Responsive menu is failing to respond to the click event

I'm facing an issue with my responsive menu on mobile phones. It should display two buttons - one for the navigation bar and the other to toggle the side bar by removing the classes hidden-xs and hidden-sm. However, I am having trouble getting the btn ...

Choose carefully when to utilize forkJoin

In a particular scenario, I need an application to generate menus based on specific contexts. Here are the definitions for menuA and menuB: // menuA example from a given source menuA() { return [ { a: 'demo1', b: &apo ...

Displaying all API data by default in Vue.js, even with filters, sorting, and search enabled - how can it be done?

I am currently utilizing Vue.js version 3 and below is the code snippet: <template> <h5>List of Products</h5> <h3>Filter</h3> <button v-on:click="resetOptions">Reset</button> & ...

display in a modal-body and jdata

Within my MySQL database, there are several columns stored, including: headline, description, place, resume Currently, I am able to display the headline and description in a modalbox using the following code. However, I now wish to also showcase the pl ...

Tips for eliminating unnecessary module js calls in Angular 9

https://i.sstatic.net/3R7sr.png Utilizing a lazy loading module has been efficient, but encountering challenges with certain modules like all-access-pass and page not found as shown in the image above. Is there a way to effectively remove unused module J ...

JQuery and PHP: Saving a rearranged set of divs in a form

Although I've searched for similar questions, none seem to address my specific issue. My problem involves a form with divs generated from a JSON array saved in a separate file. To style the form, I'm using Bootstrap and implementing JQueryUI&apo ...

Adding an object array to a new array - Step by step guide

I am working with an array of states const states = [{id:1,name:"New York",cities:[...]},{id:2,name:"California",cities:[...]}] My goal is to extract all cities and store them in a new array using methods ... const cities = [] this.s ...

Tips for updating model data when integrating jQuery Data tables with ASP.NET MVC

Managing a large amount of data returned from JSON can be complex. To tackle this, I am utilizing jQuery dataTable for sorting, filtering, and pagination purposes. The functionality is working seamlessly for sorting, searching, and paginating the data. H ...

Dispatching identification to controller after submission

I am encountering an issue with a page that contains the following code: <div class="col-sm-2 displaybutton"> <div data-point-to="displaysHeader"> @using (Html.BeginForm("Administration", "Home", FormMethod.Post)) ...

Showing a section of a DIV inside an iframe

I have implemented an HTML object in the following way: <object id="foo" name="foo" type="text/html" data="mypage.aspx"> </object> However, I do not want to display the entire content of mypage.aspx within the HTML object/iframe. In ...

Concentrate on implementing Cross-domain Ajax functionality in Opera browser

For a unique and interesting browsing experience, try using Opera 9.62 to explore the nuances of cross-sub-domain JavaScript calls with Ajax. To understand this better, follow these instructions by placing three simple files on appropriate domains. foo.ht ...

Adjusting Chart.js line graph alignment to the left

I'm curious about why my chart is not aligned to the left and how I can fix this issue. Here is the code snippet I am working with: var data = { labels: ["ID"] , datasets: [ { label: "Sensor 1" , data: [{ ...

Text displayed in a pop-up when hovering

I'm in search of suggestions for creating a text pop-up that displays when the mouse hovers over specific text. After researching numerous websites, I haven't found exactly what I need. Currently, I have a table with headers at the top and I woul ...

Guide on converting arrays and sending this information in Node.js

I managed to retrieve quiz data and now I want to enhance it by mapping each answer to its respective quiz. I have a feeling that I should use something like forEach.push, but I haven't quite figured out the exact method... const API_KEY="https: ...

Displaying data using JSON on a fabric.js canvas

I've been encountering some issues while attempting to store data in JSON and then reload it onto the canvas using fabric.js. My code is quite simple: canvas.add(new fabric.Rect({ width: 50, height: 50, fill: 'red', top: 100, left: 100 })); ...