【问题标题】:ValueError: Extra Data error when importing json file using pythonValueError:使用python导入json文件时出现额外数据错误
【发布时间】:2016-11-23 06:40:21
【问题描述】:

我正在尝试构建一个将 json 文件导入 MongoDB 的 python 脚本。我的这部分脚本不断跳转到except ValueError 以获得更大的 json 文件。我认为这与逐行解析 json 文件有关,因为非常小的 json 文件似乎可以工作。

def read(jsonFiles):
from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')
db = client[args.db]

counter = 0
for jsonFile in jsonFiles:
    with open(jsonFile, 'r') as f:
        for line in f:
            # load valid lines (should probably use rstrip)
            if len(line) < 10: continue
            try:
                db[args.collection].insert(json.loads(line))
                counter += 1
            except pymongo.errors.DuplicateKeyError as dke:
                if args.verbose:
                    print "Duplicate Key Error: ", dke
            except ValueError as e:
                if args.verbose:
                    print "Value Error: ", e

                    # friendly log message
            if 0 == counter % 100 and 0 != counter and args.verbose: print "loaded line:", counter
            if counter >= args.max:
                break

我收到以下错误消息:

Value Error:  Extra data: line 1 column 10 - line 2 column 1 (char 9 - 20)
Value Error:  Extra data: line 1 column 8 - line 2 column 1 (char 7 - 18)

【问题讨论】:

  • 文件可能不是有效的json 格式。

标签: python json mongodb pymongo


【解决方案1】:

想通了。看起来把它分成几行是错误的。这是最终代码的样子。

counter = 0
for jsonFile in jsonFiles:
    with open(jsonFile) as f:
        data = f.read()
        jsondata = json.loads(data)
        try:
            db[args.collection].insert(jsondata)
            counter += 1

【讨论】:

    【解决方案2】:

    看这个例子:

    s = """{ "data": { "one":1 } },{ "1": { "two":2 } }"""
    json.load( s )
    

    它会在你的 json 文件中产生“额外数据”错误:

    ValueError:额外数据:第 1 行第 24 列 - 第 1 行第 45 列(字符 23 - 44)

    这是因为这不是一个有效的 JSON 对象。它包含两个独立的“dict”,用冒号分隔。也许这可以帮助您找到 JSON 文件中的错误。

    this post 您可以找到更多信息。

    【讨论】:

    • 好的,所以看起来我需要定义多个字典(我的 json 文件非常大,并且在某些点有五个缩进级别),转储字典,将它们包装在一个列表中,然后转储列表。这在我的代码中看起来如何?
    猜你喜欢
    • 2016-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-13
    • 2019-04-28
    • 1970-01-01
    相关资源
    最近更新 更多