如何在Python中合并两个json字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22698244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to merge two json string in Python?
提问by
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.
我最近开始使用 Python,我试图将我的 JSON 字符串之一与现有的 JSON 字符串连接起来。我也在使用 Zookeeper,所以我从 Zookeeper 节点获取现有的 json 字符串,因为我正在使用 Python kazoo 库。
# gets the data from zookeeper
data, stat = zk.get(some_znode_path)
jsonStringA = data.decode("utf-8")
if I print jsonStringAit gives me like this -
如果我打印jsonStringA它给我这样的 -
{"error_1395946244342":"valueA","error_1395952003":"valueB"}
But if I do print json.loads(jsonString)then it prints out like this -
但如果我这样做,print json.loads(jsonString)它会像这样打印出来 -
{u'error_1395946244342': u'valueA', u'error_1395952003': u'valueB'}
Here jsonStringAwill have my existing JSON String. Now I have another key-value pair which I need to add in the exiting jsonStringA-
这里jsonStringA将有我现有的 JSON 字符串。现在我有另一个键值对,我需要在退出时添加jsonStringA-
Below is my Python code -
下面是我的 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"
My existing jsonStringAwill be like this after extracting from zookeeper -
jsonStringA从zookeeper中提取后,我的现有将是这样的-
{"error_1395946244342":"valueA","error_1395952003":"valueB"}
Now I need to append this key-value pair in the jsonStringA-
现在我需要将这个键值对附加到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"
So final JSON String will look like this -
所以最终的 JSON 字符串将如下所示 -
{"error_1395946244342":"valueA","error_1395952003":"valueB","error_1395952167":"Error Occured on machine h1 in datacenter dc3 on the step2 of process test"}
Is this possible to do?
这是可能的吗?
采纳答案by Vame
Assuming a and b are the dictionaries you want to merge:
假设 a 和 b 是您要合并的字典:
c = {key: value for (key, value) in (a.items() + b.items())}
To convert your string to python dictionary you use the following:
要将字符串转换为 python 字典,请使用以下命令:
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)
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.
但我不得不说,总的来说,您尝试做的并不是最佳实践。请阅读一些关于 python 词典的内容。
Alternative solution:
替代解决方案:
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.
实际上,如果您只使用一个数组来保存所有错误,就可以避免所有这些。
回答by Vitaly Isaev
What do you mean by merging? JSON objects are key-value data structure. What would be a key and a value in this case? I think you need to create new directory and populate it with old data:
你说的合并是什么意思?JSON 对象是键值数据结构。在这种情况下,键和值是什么?我认为您需要创建新目录并用旧数据填充它:
d = {}
d["new_key"] = jsonStringA[<key_that_you_did_not_mention_here>] + \
jsonStringB["timestamp_in_ms"]
Merging method is obviously up to you.
合并方法显然取决于您。
回答by theclaymethod
You can load both json strings into Python Dictionaries and then combine. This will only work if there are unique keys in each json string.
您可以将两个 json 字符串加载到 Python Dictionaries 中,然后合并。这仅在每个 json 字符串中有唯一键时才有效。
import json
a = json.loads(jsonStringA)
b = json.loads(jsonStringB)
c = dict(a.items() + b.items())
# or c = dict(a, **b)
回答by bschlueter
Merging json objects is fairly straight forward but has a few edge cases when dealing with key collisions. The biggest issues have to do with one object having a value of a simple type and the other having a complex type (Array or Object). You have to decide how you want to implement that. Our choice when we implemented this for json passed to chef-solo was to merge Objects and use the first source Object's value in all other cases.
合并 json 对象相当简单,但在处理键冲突时有一些边缘情况。最大的问题与具有简单类型值的对象和具有复杂类型(数组或对象)的另一个对象有关。您必须决定如何实现它。当我们为传递给 Chef-solo 的 json 实现这个时,我们的选择是合并对象并在所有其他情况下使用第一个源对象的值。
This was our solution:
这是我们的解决方案:
from collections import Mapping
import json
original = json.loads(jsonStringA)
addition = json.loads(jsonStringB)
for key, value in addition.iteritems():
if key in original:
original_value = original[key]
if isinstance(value, Mapping) and isinstance(original_value, Mapping):
merge_dicts(original_value, value)
elif not (isinstance(value, Mapping) or
isinstance(original_value, Mapping)):
original[key] = value
else:
raise ValueError('Attempting to merge {} with value {}'.format(
key, original_value))
else:
original[key] = value
You could add another case after the first case to check for lists if you want to merge those as well, or for specific cases when special keys are encountered.
您可以在第一个案例之后添加另一个案例来检查列表,如果您还想合并这些列表,或者遇到特殊键时的特定案例。
回答by P i
As of Python 3.5, you can merge two dicts with:
从 Python 3.5 开始,您可以将两个字典合并为:
merged = {**dictA, **dictB}
(https://www.python.org/dev/peps/pep-0448/)
( https://www.python.org/dev/peps/pep-0448/)
So:
所以:
jsonMerged = {**json.loads(jsonStringA), **json.loads(jsonStringB)}
asString = json.dumps(jsonMerged)
etc.
等等。
回答by cowlinator
To append key-value pairs to a json string, you can use dict.update: dictA.update(dictB).
要将键值对附加到 json 字符串,您可以使用dict.update: dictA.update(dictB)。
For your case, this will look like this:
对于您的情况,这将如下所示:
dictA = json.loads(jsonStringA)
dictB = json.loads('{"error_1395952167":"Error Occured on machine h1 in datacenter dc3 on the step2 of process test"}')
dictA.update(dictB)
jsonStringA = json.dumps(dictA)
Note that key collisions will cause values in dictBoverriding dictA.
请注意,键冲突将导致dictB覆盖中的值dictA。

