Amit Pal
Amit Pal

Reputation: 11052

How to remove unicode character from a list in Django?

I have a following list of list in Django:

[['Host Name', 'No. of Events'], [u'12.23.21.23', 0], [u'2.152.0.2', 2]]

To get the above list, I wrote the following code in my views:

 def graph_analysis(request):
    event_host, event_alerts = ([] for x in range(2))
    event_alerts.append(['Host Name', 'No. of Events'])
    host_ipv4 = [et for et in get_hosts(user=request.user)]
    event = get_events(source_hosts=host_ipv4)
    for x in host_ipv4:
        event_host.append(x.ipv4)
        event_alerts.append([x.ipv4,get_host_count(x,event)])
    extra_context = {
    ####

Now i am using this list in my Javascript varibale. Everything is fine except the unicode character. I want to remove it. In short i want the above list as follow:

[['Host Name', 'No. of Events'], ['12.23.21.23', 0], ['2.152.0.2', 2]]

What should i do?

Upvotes: 2

Views: 10512

Answers (2)

Silas Ray
Silas Ray

Reputation: 26160

import json
list_ = #your content list here
list_as_json = json.dumps(list_)

You aren't actually removing anything. The u's show up because the elements in those lists are unicode strings, and the __repr__() for a unicode string prints the leading u to differentiate it from a non-unicode string. json.dumps() treats the content of unicode and non-unicode strings the same (at least as far as it matters for this question) when it converts the list to a json string, so you don't get any u identifiers.

Upvotes: 6

Marcin
Marcin

Reputation: 49826

There isn't "a unicode character" here. You have a list containing unicode strings which you want to output as json. You need to encode the unicode string (an abstract representation of text) as a byte string (a sequence of bytes). The way you do that is:

u'12.23.21.23'.encode('utf8')

Upvotes: 7

Related Questions