【问题标题】:Python JSON data load perplexing "expecting , delimiter" errorPython JSON数据加载令人困惑的“预期,分隔符”错误
【发布时间】:2018-05-04 02:32:23
【问题描述】:

尝试实现此代码并不断收到以下错误。我已经搜索并尝试了一切,但没有什么能让我通过它。

import json
import sys
import re
import os
reload(sys)
sys.setdefaultencoding('utf8')
path = '/Users/.../'  #(The actual path is in my code)
textfiles = []
for root, dirs, files in os.walk(r'/Users/.../'):
    for file in files:
        if file.endswith(".txt"):
            textfiles.append(file)
        for filename in textfiles:
            with open(path + filename) as json_data:
                data = json.load(json_data)
                opinion = data['plain_text']
                f = open(path + filename, 'w')
                f.write(opinion)
                f.close()

然后,我不断收到此错误:

ValueError: Expecting , delimiter: line 17 column 3 (char 765)

【问题讨论】:

  • 问题出在 json 文件中。这是不正确的..你必须看看json。
  • 谢谢。那很有帮助。我将停止查看代码并检查文件。
  • 您也许可以使用 JSON 验证器。它可以节省您的肉眼查看时间。
  • Johnashu:有什么建议,因为我使用这段代码来处理数千个 JSON 文件?我将如何隔离导致此错误的一个 JSON 文件? (如果可能的话)
  • 我提供了一个答案,告诉你如何捕捉错误。

标签: python json delimiter


【解决方案1】:

显然您的问题出在 JSON 文件中。但是是哪一个?在哪里??

如果您输入try/except 子句,您可以记录并查看导致问题的文件,以便您可以更轻松地进行调试。

import json
import sys
import re
import os
reload(sys)
sys.setdefaultencoding('utf8')
path = '/Users/.../'  (The actual path is in my code)
textfiles = []
for root, dirs, files in os.walk(r'/Users/.../'):
    for file in files:
        if file.endswith(".txt"):
            textfiles.append(file)
        for filename in textfiles:
            try:
                with open(path + filename) as json_data:
                    data = json.load(json_data)
                    opinion = data['plain_text']
                    f = open(path + filename, 'w')
                    f.write(opinion)
                    f.close()
            except ValueError as e:
                print(filename) # Gives the filename
                print(e)  # Gives the location of the problem in the file

它还应该继续遍历文件并在有问题的文件上提供错误。

您甚至可以保存到 log.txt 以供以后处理..

这是一个小例子

lst = [1, 2, '3', 4, 5]

for i in lst:
    try:
        l = 123 + i
        print(l)
    except Exception as e:
        print(e)

输出:

124
125
unsupported operand type(s) for +: 'int' and 'str'
127
128

【讨论】:

  • 太棒了。谢谢!我将使用它并将其合并并获取错误日志。太好了。
【解决方案2】:

这表示您的一个 JSON 文件的第 17 行缺少逗号。哪一个?错误中应该有更多上下文,但如果没有,您应该尝试通过处理较小批量的文件来隔离它。

另外,为什么 JSON 数据中有 700 多个字符?

【讨论】:

  • 我实际上有一批 JSON 文件。它们是从网上抓取的长文档,其中许多包含 700 多个字符。现在的挑战是,该错误并不表明我要处理的文件夹中的 100,000 个文件中的哪个文件具有错误的 JSON。所以,这是另一个挑战。
  • 二分查找呢?将它们分成两批,每批大小为 50K。然后是25K,以此类推。但实际上,错误应该说明它正在谈论的是哪个文件。
猜你喜欢
  • 1970-01-01
  • 2016-03-24
  • 2018-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-16
  • 2012-09-12
  • 1970-01-01
相关资源
最近更新 更多