多个json字典python [英] multiple json dictionaries python

查看:164
本文介绍了多个json字典python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有多个json字典的json文件: 格式如下

I have a json file with multiple json dictionaries: the format is as following

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

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

How can I convert this to one json dictionary format as following:

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

推荐答案

在这里已经大部分回答:

Already mostly answered here: Importing wrongly concatenated JSONs in python

这说明了如何使用json.JSONDecoder方法raw_decode()从它们的串联列表(不是有效的JSON)中拾取每个JSON元素.剩下的事情很简单,就是将字符串'{"items":['element1","element2,... "]"串联在一起,或者将它们累加为一个列表,并用单项dict和if将其包装起来.必需,使用json.dumps

That shows you how to pick up each JSON element from a concatenated list of them (which is not valid JSON) using json.JSONDecoder method raw_decode(). The rest is a simple matter of concatenating strings '{"items":[', element1, ",", element2, ... "]" or alternatively, accumulating them as a list, wrapping that with a one-item dict and if required, dumping that json as a string with 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 )

这篇关于多个json字典python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆