如何在python中加载多个json对象

时间:2018-09-25 19:09:54

标签: python json

我在 json 文件中有以下格式的10,000个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)
>>> 

我已经阅读了相关问题,但是没有一个帮助。

5 个答案:

答案 0 :(得分:5)

您描述的文件内容不是有效的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}]')

答案 1 :(得分:1)

正如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字符串列表

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

最后,遍历json字符串列表

for i in data:
    print json.loads(i)

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

我相信,如果您不想更改源文件,最好的方法是使用json.JSONDecoder.raw_decode() 它将允许您遍历文件中的每个有效json对象

from json import JSONDecoder, JSONDecodeError

decoder = JSONDecoder()
content = '{ "a": 1,  "b": 2,  "c": { "d":3 }}{ "e": 4, "f": 5,  "g": {"h":6 } }'

pos = 0
while True:
    try:
        o, pos = decoder.raw_decode(content, pos)
        print(o)
    except JSONDecodeError:
        break

将打印两个Json对象

答案 4 :(得分:0)

@Thiago 的答案对我有用,但前提是 pos 加一,否则它总是只打印一个对象

就这样:

from json import JSONDecoder, JSONDecodeError

def json_decoder(data):
    decoder = JSONDecoder()
    pos = 0
    result = []
    while True:
        try:
            o, pos = decoder.raw_decode(data, pos)
            result.append(o)
            pos +=1
        except JSONDecodeError:
            break
    return result