如何在Python中合并两个json字符串?

我最近开始使用Python,并且尝试将我的JSON字符串之一与现有JSON字符串连接在一起。我也在与Zookeeper一起工作,所以当我使用Python

kazoo库时,我从zookeeper节点获取了现有的json字符串

# gets the data from zookeeper

data, stat = zk.get(some_znode_path)

jsonStringA = data.decode("utf-8")

如果我打印,jsonStringA它会给我这样的感觉-

{"error_1395946244342":"valueA","error_1395952003":"valueB"}

但是,如果我这样做,print json.loads(jsonString)它会像这样打印出来-

{u'error_1395946244342': u'valueA', u'error_1395952003': u'valueB'}

这里jsonStringA将有我现有的JSON字符串。现在我有另一个键值对,我需要在出口添加jsonStringA-

以下是我的Python代码-

# gets the data from zookeeper

data, stat = zk.get(some_znode_path)

jsonStringA = data.decode("utf-8")

timestamp_in_ms = "error_"+str(int(round(time.time() * 1000)))

node = "/pp/tf/test/v1"

a,b,c,d = node.split("/")[1:]

host_info = "h1"

local_dc = "dc3"

step = "step2"

jsonStringA从Zookeeper提取后,我的现有状态将如下所示:

{"error_1395946244342":"valueA","error_1395952003":"valueB"}

现在,我需要将此键值对添加到jsonStringA-

"timestamp_in_ms":"Error Occured on machine "+host_info+" in datacenter "+ local_dc +" on the "+ step +" of process "+ c +"

简而言之,我需要合并以下键值对-

"error_1395952167":"Error Occured on machine h1 in datacenter dc3 on the step2 of process test"

因此,最终的JSON字符串将如下所示-

{"error_1395946244342":"valueA","error_1395952003":"valueB","error_1395952167":"Error Occured on machine h1 in datacenter dc3 on the step2 of process test"}

这可能吗?

回答:

假设a和b是要合并的字典:

c = {key: value for (key, value) in (a.items() + b.items())}

要将字符串转换为python字典,请使用以下命令:

import json

my_dict = json.loads(json_str)


# test cases for jsonStringA and jsonStringB according to your data input

jsonStringA = '{"error_1395946244342":"valueA","error_1395952003":"valueB"}'

jsonStringB = '{"error_%d":"Error Occured on machine %s in datacenter %s on the %s of process %s"}' % (timestamp_number, host_info, local_dc, step, c)

# now we have two json STRINGS

import json

dictA = json.loads(jsonStringA)

dictB = json.loads(jsonStringB)

merged_dict = {key: value for (key, value) in (dictA.items() + dictB.items())}

# string dump of the merged dict

jsonString_merged = json.dumps(merged_dict)

但是我不得不说,总的来说,您尝试做的并不是最佳实践。请阅读有关python词典的内容。


jsonStringA = get_my_value_as_string_from_somewhere()

errors_dict = json.loads(jsonStringA)

new_error_str = "Error Ocurred in datacenter %s blah for step %s blah" % (datacenter, step)

new_error_key = "error_%d" % (timestamp_number)

errors_dict[new_error_key] = new_error_str

# and if I want to export it somewhere I use the following

write_my_dict_to_a_file_as_string(json.dumps(errors_dict))

实际上,如果仅使用数组来保存所有错误,则可以避免所有这些情况。

以上是 如何在Python中合并两个json字符串? 的全部内容, 来源链接: utcz.com/qa/433362.html

回到顶部