質問

I am working with Python and Zookeeper as I am using kazoo library in Python. This question is not about Zookeeper or kazoo library. I guess this is mainly related to Python.

Below are my two variables -

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)

And now I need to use these two variables to make a byte json string and then write the that json string as the data in the Zookeeper node so below is the syntax by which we create a node and write the data as well -

zk.create(date_znode_path, b'{"'+new_error_key+'":"' + new_error_str + '"}', None, True)

Somehow the above line throws an exception as -

TypeError: value must be a byte string

Any thoughts what wrong I am doing here? I am trying to make a JSON String of above variables.

Here is details about kazoo library

UPDATE:-

If I use this syntax, then it works fine -

b'{"hostname":"' + get_hostname() + '"}', None, True)

I can see data like this -

{"hostname":"machineA"}
役に立ちましたか?

解決

You should use json module:

import json
zk.create(date_znode_path, json.dumps({new_error_key : new_error_str}, ensure_ascii=True), None, True)

Manually constructing json is tricky, what if input contains quotes? It is always better to use tools that can escape everything and are well tested against all edge cases.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top