python - 多个json字典python

标签 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"}]}

最佳答案

大部分已在此处回答: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 )

关于python - 多个json字典python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37002806/

相关文章:

python - 如何从脆皮形式的 View 中更改提交按钮文本?

python - 什么 HTTP 框架用于简单但可扩展的应用程序?

python - 计算在某个范围内具有特定值的键的数量

android - 从服务器改造响应 OK 200 但我得到空值

c# - 放置后如何从 philips hue 桥获取 http json 响应

javascript - JSON 序列化在 loadFromJSON 之后忽略 fabric.js 中的自定义属性

python - 在 Python For 循环中重用迭代器变量

python - 事后清理存储在源存储库中的 virtualenv 中的 .pyc 文件吗?

javascript - 如何处理多个单独的 json 响应?

使用 json.loads 时出现 Python 段错误——将 JSON 加载到列表中的替代方法?