本文介绍了将两个JSON对象合并为一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个JSON对象.一种是使用json,dumps()转换的python数组,另一种包含来自数据库的记录,并使用json序列化器进行序列化.我想将它们组合成一个JSON对象.
I have two JSON objects. One is python array which is converted using json,dumps() and other contains records from database and is serialized using json serializer. I want to combine them into a single JSON object.
例如:
obj1 = ["a1", "a2", "a3"]
obj2 = [
{
"pk": "e1",
"model": "AB.abc",
"fields": {
"e_desc": "abcd"
}
},
{
"pk": "e1",
"model": "AB.abc",
"fields": {
"e_desc": "hij"
}
},
]
我想将它们合并为单个对象,如下所示:
I want to merge them into single object as below:
finalObj = {
obj1:["a1", "a2", "a3"],
obj2: [
{
"pk": "e1",
"model": "AB.abc",
"fields": {
"e_desc": "abcd"
}
},
{
"pk": "e1",
"model": "AB.abc",
"fields": {
"e_desc": "hij"
}
},
]
}
我该怎么做?
推荐答案
一旦它们为JSON格式,您将无法执行-JSON只是文本.您需要先在Python中将它们组合起来:
You can't do it once they're in JSON format - JSON is just text. You need to combine them in Python first:
data = { 'obj1' : obj1, 'obj2' : obj2 }
json.dumps(data)
这篇关于将两个JSON对象合并为一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!