Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

298
Visualizações
How to parse a json dumped python dict as javascript object in django template

I have a python code which converts the normal dict into JSON as follows

groups = {
    'g_1': [
        {'name': 'something', 'id': '1'}, 
        {'name': 'something', 'id': '1'}
    ], 
    'g_2': [
        {'name': 'something', 'id': '1'}, 
        {'name': 'something', 'id': '1'}
    ]
}

I have used json.dumps to convert that to a json as follows

import json
groups = json.dumps(groups)

I want to read the data in javascript as an object. How to I access it?

I tried var groups=JSON.parse({{ groups }}) it didn't work out. Help me in parsing the data as javascript object.

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

This should work:

var groups = JSON.parse('{{ groups|safe }}');

about 4 years ago · Santiago Trujillo Relatório

0

try:

var groups = JSON && JSON.parse({{ groups }})|| $.parseJSON({{ groups }});
about 4 years ago · Santiago Trujillo Relatório

0

You may have troubles with ' character trying to run var groups = "{{ groups|safe }}"; or var groups = '{{ groups|safe }}';. If both answers don't work try this solution:

function escapeRegExp(str) {
    return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
function replaceAll(str, find, replace) {
    return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}

var str = "{{ groups|safe }}";
var new_str = replaceAll(str, "'", "\"");

var groups = JSON.parse(new_str);

I had to replace all ' to " in the dictionary for JSON.parse to work. To know more about these functions check Stack How to replace all occurrences of a string in JavaScript question.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda