在Python中使用MySQLdb中的Jsonifying位

时间:2013-02-09 04:50:54

标签: python mysql-python

我在Python中使用MySQLdb读取MySQL记录。其中一列是有点的。 当我使用\\u0000将其转换为JSON时,它在Python控制台上显示为\\u0001json.dumps(它显示为\x00在转换之前)并将其发送到浏览器,浏览器不显示任何内容。我假设它是因为它不知道Unicode的字符。

我是否有办法通过客户端或服务器上的操作获取这些值的Javascript TrueFalse

1 个答案:

答案 0 :(得分:1)

在服务器端操作它就像:

import json

def convert_to_bool(bstring):
    return True if bstring == b'\x00' else False

示例用法:

your_byte_string = b'\x00'
# you can write also
# your_byte_string = u'\u0000'

print(json.dumps(convert_to_bool(your_byte_string))) 

# >>> true

your_byte_string = b'\x01'
# you can write also
# your_byte_string = u'\u0001'

print(json.dumps(convert_to_bool(your_byte_string)))

# >>> false

然后,最终你可能希望添加一些代码 - 如果该字段为真,则显示图像。这可以在服务器端或客户端完成。

服务器端

如果您不打算在javascript代码中使用布尔变量,则可以直接发送预期的HTML:

if convert_to_bool(your_byte_string):
    # here I'm just printing it but you should use the dumped string as a json response
    print(json.dumps('The field is <b>true</b>!'))
else:
    print(json.dumps('Unfortunately the field is <b>false</b>.'))

客户端

如果你正在使用json,我想你知道如何做到这一点,它是基本的javascript,但为了完整起见,这里是代码:

// javascript code
// yourdata is the field value, retrieved by the ajax call 

if (yourdata) {
    alert('The field is true!');    
} else {
    alert('The field is false!');
}