2

I'm trying to pass Python list to use it as Javascript array in HTML file, but when I check the passed Python list in Javascript level, the console log says it's string.

I'm trying to do that in Django environment.

Django views.py

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['names'] = list(
        Store.objects.values_list('businessName', flat=True))

    return context

index.html

<span data-names="{{ names }}">...</span>
<script>
    console.log(type($('span').attr('data-names')));
</script>

The console says it's string type. Did I miss any middle step there?

console.log result

['Michael Kors', 'Luca + Grae', 'Rebecca Minkoff', 'Aritzia', 'Nest Boutique', 'Ruby Claire Boutique', 'Bella Ella Boutique', 'Called to Surf', 'Adidas', 'Lime Lush', 'Farfetch', 'AGACI', 'The Mint Julep Boutique', 'Free People', 'Current Boutique', 'Hazel and Olive', 'DownEast Basics', 'Roolee', 'J.Crew']
2
  • If python is putting out a JSON array here then wrapping it in JSON.parse might work to get you a JS object. Commented Nov 7, 2018 at 23:19
  • MDN Docs at the bottom of this section is says that all data-* attributes are strings. Commented Nov 7, 2018 at 23:21

2 Answers 2

1

According to the MDN Docs all data-* attributes are saved as strings. To get a proper JSON type object you will need to use JSON.parse

<span data-names="{{ names }}">...</span>
<script>
    const data = JSON.parse($('span').attr('data-names'));
    console.log(data);
</script>

According to this question you can pass JSON from django (version >= 1.7) like

from django.http import JsonResponse
return JsonResponse({'foo':'bar'})
Sign up to request clarification or add additional context in comments.

3 Comments

I tried JSON.parse, but it throws Uncaught SyntaxError: Unexpected token ' in JSON at position 1 at JSON.parse (<anonymous>), so I tried JSON.parse(JSON.stringify(...)), but it still returns string.
I put the console.log result in the original post. Can you check that?
I don't know django but here is another question about returning JSON from django.
1
<script>
    var names = {{ names|safe }}
</script>

safe tag is one option.

1 Comment

It seems like Javascript doens't read {{ names|safe }}.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.