Py学习  »  Python

如何在Python中加载多个JSON对象

krishna • 7 年前 • 1472 次点击  

我有10000个JSON对象 杰森 文件格式如下:

{ "a": 1,
  "b" : 2,
  "c" : {
          "d":3
        }
}{ "e" : 4,
  "f" : 5,
  "g" : {
         "h":6
        }
}

如何将这些作为JSON对象加载?

我尝试的两种方法都有相应的错误:

方法1:

>>> with open('test1.json') as jsonfile:
...     for line in jsonfile:
...             data = json.loads(line)
... 

错误:

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
  File "/usr/lib/python3.5/json/__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.5/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.5/json/decoder.py", line 355, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 2 column 1 (char 10)

方法2:

>>> with open('test1.json') as jsonfile:
...     data = json.load(jsonfile)      
... 

错误:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/usr/lib/python3.5/json/__init__.py", line 268, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "/usr/lib/python3.5/json/__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.5/json/decoder.py", line 342, in decode
    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 7 column 1 (char 46)
>>> 

我读过相关的问题,但都没有帮助。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/30651
文章 [ 3 ]  |  最新文章 7 年前
ARR
Reply   •   1 楼
ARR    7 年前
[
    { 
      "a": 1,
      "b" : 2,
      "c" : {
              "d":3
            }
    },
    { 
      "e" : 4,
      "f" : 5,
      "g" : {
             "h":6
            }
    }
]

首先,您的JSON文件应该 像这样,第二次像json.loads一样加载文件(file.read())

Mauro Baraldi
Reply   •   2 楼
Mauro Baraldi    7 年前

正如Daniel在评论中所说,重点关注JSON块的开始/结束模式。 }{ .

将所有数据加载到一个字符串中,将此模式替换为您可以处理的模式,并将其拆分为有效JSON数据的字符串列表。最后,遍历列表。

{ "a": 1,
"b" : 2,
"c" : {
        "d":3
        }
}{ "e" : 4,
"f" : 5,
"g" : {
        "h":6
        }
}

将数据加载到JSON有效字符串列表中

with open('/home/mauro/workspace/test.json') as fp:
    data = fp.read()

替换图案

data = data.replace('}{', '}\n\n{')

然后,将其拆分为JSON字符串valid列表

data = data.split('\n\n')

最后,遍历JSON字符串列表

for i in data:
    print json.loads(i)
krishna
Reply   •   3 楼
krishna    7 年前

您描述的文件内容不是有效的JSON对象这就是为什么bot方法不起作用的原因。

转换你可以加载的内容 json.load(fd) 你必须:

  1. 添加一个 [ 在文件的开头
  2. 添加一个 , 在每个对象之间
  3. 添加一个 ] 在文件的最后

然后您可以使用方法2。 例如:

[ { "a": 1,
    "b" : 2,
    "c" : {
      "d":3
    }
  }, { "e" : 4,
       "f" : 5,
       "g" : {
         "h":6
       }
  }
]

是有效的JSON数组

如果文件格式与您描述的完全相同,您可以

with open(filename, 'r') as infile:
    data = infile.read()
    new_data = data.replace('}{', '},{')
    json_data = json.loads(f'[{new_data}]')