1

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']
Jay P.
  • 2,420
  • 6
  • 36
  • 71
  • If python is putting out a JSON array here then wrapping it in `JSON.parse` might work to get you a JS object. – Benjamin Brettsworth Nov 07 '18 at 23:19
  • [MDN Docs](https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes#JavaScript_access) at the bottom of this section is says that all `data-*` attributes are strings. – pmkro Nov 07 '18 at 23:21

2 Answers2

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'})
pmkro
  • 2,542
  • 2
  • 17
  • 25
  • I tried `JSON.parse`, but it throws `Uncaught SyntaxError: Unexpected token ' in JSON at position 1 at JSON.parse ()`, so I tried `JSON.parse(JSON.stringify(...))`, but it still returns string. – Jay P. Nov 07 '18 at 23:47
  • I put the console.log result in the original post. Can you check that? – Jay P. Nov 07 '18 at 23:47
  • I don't know django but [here is another question](https://stackoverflow.com/questions/2428092/creating-a-json-response-using-django-and-python) about returning JSON from django. – pmkro Nov 07 '18 at 23:50
1
<script>
    var names = {{ names|safe }}
</script>

safe tag is one option.

Ykh
  • 7,567
  • 1
  • 22
  • 31