Skip to main content
 首页 » 编程设计

python之多个json字典python

2024年10月24日9cyq1162

我有一个包含多个 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"}]} 

请您参考如下方法:

大部分已在此处回答:Importing wrongly concatenated JSONs in python

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

确定扩展

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 )