Python json.loads 无法解析 json 字符串

标签 python json

我只是在做一个副业,在获取 json 模块来解析我存储在文本文件中的 json 对象时遇到了问题。文本文件包含换行符分隔的 json 对象列表。

到目前为止,我已经确认这段代码正在检索每个完整的 json 行,然后将其提供给 json.loads():

def load_save_game(file_name):
    save_game = []
    with open(file_name) as f:
        for line in f.readline():
            save_game.append(json.loads(line))
    return save_game

当我运行它时,我得到了相当长的回溯:

Traceback (most recent call last):
  File ____, line 70, in <module> 
    main()
  File ____, line 66, in main
    view = ViewerWindow(load_save_game('played/20_05_2016 16-04-31.txt'))
  File ____, line 60, in load_save_game
    save_game.append(json.loads(line))
  File "C:\Python27\lib\json\__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "C:\Python27\lib\json\decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Python27\lib\json\decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting object: line 1 column 1 (char 0)

我怀疑问题可能与编码有关,但在调查此事后,我发现 JSON 库可能对诸如真值大写、悬空逗号和单引号而不是双引号之类的事情很挑剔引号。

Python 2.7 似乎使用了 RFC 7159 and ECMA 404 json规范,所以我用了免费的在线json validator查看 json 格式是否错误。它已针对所有 json 标准成功验证,因此 python 应该对输入非常满意。

我主持了一行 json on pastebin ,唯一的区别是 the file没有空格 ,我也上传了。

我在网上寻找解决方案并尝试了几种不同的解决方案,例如将真值大写、替换所有单引号以及从 ascii 解码文本。

最佳答案

您正在遍历第一行的字符:

for line in f.readline():

f.readline() 返回一个字符串,即文件的第一行。这里根本不需要调用readline(),直接遍历文件对象即可:

with open(file_name) as f:
    for line in f:
        if line.strip():
            save_game.append(json.loads(line))

我添加了一个额外的测试来跳过空行(文件末尾很容易包含一个空行)。

你也可以把上面的变成一个列表理解:

def load_save_game(file_name):
    with open(file_name) as f:
        return [json.loads(l) for l in f if l.strip()]

请注意,如果您的 JSON 文档本身不包含换行符,则上述仅适用。如果文件中只有一个 JSON 文档,请使用 json.load(f)(无循环),或者使用 different technique在文档本身中使用换行符解析多个 JSON 文档。

无论有无 line.strip() 调用,以上代码都适用于您提供的示例文件:

>>> len(load_save_game(os.path.expanduser('~/Downloads/20_05_2016_16-04-31.txt')))
301

关于Python json.loads 无法解析 json 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37387163/

相关文章:

python - Redis key 管理

python - python 中,如果前两个元素为 0 和 1,如何获取矩阵的行数?

c# - fusionChart 未使用 Json 和 C# 加载动态数据

python - 使用 python 和 lxml 从大型 HTML 文件中解析和提取信息

python - PyMC:马尔可夫系统中的参数估计

python - CentOS免root安装gdal

json - 具有多个动态命名字段的 Golang Json 解码

json - 如何在Play Framework中将Scala Map序列化为Json?

ios - 如何开始在 xcode 中创建 json 解析器( Storyboard)

javascript - 如何将 JSON 对象从 Java/Prime Faces 传递到 GOJS javascript 文件