多个json字典python

时间:2016-05-03 11:24:43

标签: python json

我有一个包含多个json词典的json文件: 格式如下

{"x":"1", "y":"2", "z": "3"}{"x": "2","y":"3", "z":"4"}{"x":"3", "y":"4", "z":"5"}

如何将此转换为一种json字典格式,如下所示:

{"items":[{"x":"1", "y":"2", "z": "3"},{"x": "2","y":"3", "z":"4"},{"x":"3", "y":"4", "z":"5"}]}

1 个答案:

答案 0 :(得分:2)

这里已经大部分回答:Importing wrongly concatenated JSONs in python

它向您展示了如何使用json.JSONDecoder方法raw_decode()从它们的连续列表中获取每个JSON元素(这是无效的JSON)。剩下的就是连接字符串'{"items":['element1","element2,... "]",或者将它们累积为列表,用一项dict包装它,如果需要,将json转换为带有json.dumps的字符串

好的扩展

import json
d = json.JSONDecoder()

# get your concatenated json into x, for example maybe
x = open('myfile.json','r').read()

jlist=[]
while True:
   try:
      j,n = d.raw_decode(x) 
      jlist.append(j)
   except ValueError: 
      break
   x=x[n:]

# my original thought was
result = '{"items":[' + 
     ','.join( [ str(s) for s in jlist] ) +
     ']'

# but this is neater
result = json.dumps( { "items":jlist })

# and of course if you want it for programmatic use, just
result_as_json = dict( items=jlist )