我正在使用Python和Zookeeper,因为我在Python中使用kazoo库。这个问题与Zookeeper或kazoo库无关。我想这主要与Python有关。
以下是我的两个变量 -
new_error_str = "Error occurred on machine %s in datacenter %s on the %s of process %s" % (host_info, local_dc, step, process_name)
new_error_key = "error_%s" % (timestamp_in_ms)
现在我需要使用这两个变量来创建一个字节json字符串,然后将该json字符串写为Zookeeper节点中的数据,所以下面是我们创建节点并写入数据的语法 -
zk.create(date_znode_path, b'{"'+new_error_key+'":"' + new_error_str + '"}', None, True)
不知何故,上面的行抛出异常为 -
TypeError: value must be a byte string
有什么想法我在这里做错了什么?我正在尝试制作上述变量的JSON字符串。
的详细信息更新: -
如果我使用这种语法,那么它可以正常工作 -
b'{"hostname":"' + get_hostname() + '"}', None, True)
我可以看到这样的数据 -
{"hostname":"machineA"}
答案 0 :(得分:2)
你应该使用json模块:
import json
zk.create(date_znode_path, json.dumps({new_error_key : new_error_str}, ensure_ascii=True), None, True)
手动构建json很棘手,如果输入包含引号怎么办?最好使用可以逃避一切的工具,并针对所有边缘情况进行充分测试。