如何在Python中合并两个json字符串? [英] How to merge two json string in Python?

查看:312
本文介绍了如何在Python中合并两个json字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始使用Python,并且尝试将我的JSON字符串之一与现有JSON字符串连接在一起.我也在与Zookeeper合作,所以当我使用Python kazoo库时,我从zookeeper节点获取了现有的json字符串.

I recently started working with Python and I am trying to concatenate one of my JSON String with existing JSON String. I am also working with Zookeeper so I get the existing json string from zookeeper node as I am using Python kazoo library.

# gets the data from zookeeper
data, stat = zk.get(some_znode_path)
jsonStringA = data.decode("utf-8")

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

if I print jsonStringA it gives me like this -

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

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

But if I do print json.loads(jsonString) then it prints out like this -

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

此处jsonStringA将具有我现有的JSON字符串.现在,我有另一个键值对,需要在退出的jsonStringA-

Here jsonStringA will have my existing JSON String. Now I have another key-value pair which I need to add in the exiting jsonStringA -

下面是我的Python代码-

Below is my Python code -

# 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"

从Zookeeper中提取后,我现有的jsonStringA将会是这样-

My existing jsonStringA will be like this after extracting from zookeeper -

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

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

Now I need to append this key-value pair in the jsonStringA -

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

因此,简而言之,我需要在键值对下面合并-

So in short I need to merge below key-value pair -

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

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

So final JSON String will look like this -

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

这可能吗?

推荐答案

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

Assuming a and b are the dictionaries you want to merge:

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

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

To convert your string to python dictionary you use the following:

import json
my_dict = json.loads(json_str)


更新:使用字符串的完整代码:


Update: full code using strings:

# 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词典的内容.

But I have to say that in general what you are trying to do is not the best practice. Please read a bit on python dictionaries.

替代解决方案:

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))

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

And actually you can avoid all these if you just use an array to hold all your errors.

这篇关于如何在Python中合并两个json字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆