结合两个不带“或”的json字符串

时间:2019-07-17 21:26:49

标签: python json python-3.x

我有两个JSON字符串

字符串1:

{"step":"example step", "data":"example data", "result":"example result"}

字符串2:

{"attachments":[ { "data":"gsddfgdsfg...(base64) ", "filename":"example1.txt", "contentType":"plain/text" } ] }

我需要将两者结合起来: 预期对象:

{
   "step":"example step",
   "data":"example data",
   "result":"example result",
   "attachments":[
      {
         "data":"gsddfgdsfg...(base64) ",
         "filename":"example1.txt",
         "contentType":"plain/text"
      },
      {
         "data":"gsddfgdsfg...(base64) ",
         "filename":"example2.txt",
         "contentType":"plain/text"
      }
   ]
}

在每次尝试中,第二个字符串都会在数组周围出现'或',这将不起作用。

1 个答案:

答案 0 :(得分:0)

您不应尝试将它们作为字符串进行操作-这将是脆弱的并且非常针对字符串。相反,将字符串解析为字典,执行所需的任何操作,然后将它们转回JSON字符串:

import json

s1 = '{"step":"example step", "data":"example data", "result":"example result"}'
s2 = '{"attachments":[ { "data":"gsddfgdsfg...(base64) ", "filename":"example1.txt", "contentType":"plain/text" } ] }'

d1 = json.loads(s1)
d2 = json.loads(s2)

d1.update(d2)

json.dumps(d1)

这将为您提供一个干净的json字符串:

'{"step": "example step", "data": "example data", "result": "example result", "attachments": [{"data": "gsddfgdsfg...(base64) ", "filename": "example1.txt", "contentType": "plain/text"}]}'

of如果您想要对象而不是字符串,那么d1现在是:

{'step': 'example step',
 'data': 'example data',
 'result': 'example result',
 'attachments': [{'data': 'gsddfgdsfg...(base64) ',
   'filename': 'example1.txt',
   'contentType': 'plain/text'}]}