如何从Django中的列表中删除unicode字符?

Ami*_*Pal 1 python django django-views python-2.7

我在Django中有以下列表:

[['Host Name', 'No. of Events'], [u'12.23.21.23', 0], [u'2.152.0.2', 2]]
Run Code Online (Sandbox Code Playgroud)

为了得到上面的列表,我在我的代码中编写了以下代码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 = {
    ####
Run Code Online (Sandbox Code Playgroud)

现在我在我的Javascript varibale中使用此列表.除了unicode角色外,一切都很好.我想删除它.总之,我想要上面的列表如下:

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

我该怎么办?

Mar*_*cin 7

这里没有"unicode".您有一个包含要作为json输出的unicode字符串的列表.您需要将unicode字符串(文本的抽象表示)编码为字节字符串(字节序列).你这样做的方式是:

u'12.23.21.23'.encode('utf8')
Run Code Online (Sandbox Code Playgroud)


Sil*_*Ray 6

import json
list_ = #your content list here
list_as_json = json.dumps(list_)
Run Code Online (Sandbox Code Playgroud)

你实际上并没有删除任何东西.u出现是因为这些列表中的元素是unicode字符串,而__repr__()unicode字符串打印出前导u以区别于非unicode字符串. json.dumps()在将列表转换为json字符串时,将unicode和非unicode字符串的内容视为相同(至少就此问题而言重要),因此您不会获得任何u标识符.