Python中的JSON.loads()ValueError额外数据

2024-05-16 01:39:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从JSON提要中读取单个值。以下是feed数据的示例:

{
    "sendtoken": "token1",
    "bytes_transferred": 0,
    "num_retries": 0,
    "timestamp": 1414395374,
    "queue_time": 975,
    "message": "internalerror",
    "id": "mailerX",
    "m0": {
        "binding_group": "domain.com",
        "recipient_domain": "hotmail.com",
        "recipient_local": "destination",
        "sender_domain": "domain.com",
        "binding": "mail.domain.com",
        "message_id": "C1/34-54876-D36FA645",
        "api_credential": "creds",
        "sender_local": "localstring"
    },
    "rejecting_ip": "145.5.5.5",
    "type": "alpha",
    "message_stage": 3
}
{
    "sendtoken": "token2",
    "bytes_transferred": 0,
    "num_retries": 0,
    "timestamp": 1414397568,
    "queue_time": 538,
    "message": "internal error,
    "id": "mailerX",
    "m0": {
        "binding_group": "domain.com",
        "recipient_domain": "hotmail.com",
        "recipient_local": "destination",
        "sender_domain": "domain.com",
        "binding": "mail.domain.com",
        "message_id": "C1/34-54876-D36FA645",
        "api_credential": "creds",
        "sender_local": "localstring"
    },
    "rejecting_ip": "145.5.5.5",
    "type": "alpha",
    "message_stage": 3
}

我不能共享实际的URL,但是上面是大约150个结果中的前两个,如果我运行

print results

json.loads()

行。

我的代码:

import urllib2
import json

results = urllib2.urlopen(url).read()
jsondata = json.loads(results)

for row in jsondata:
     print row['sendtoken']
     print row['recipient_domain']

我想输出如下

token1
hotmail.com

对于每个条目。

我得到这个错误:

ValueError: Extra data: line 2 column 1 - line 133 column 1 (char 583 - 77680)

我不是Python专家,这是我第一次使用JSON。我花了很多时间在google和Stack Overflow上,但找不到适合我特定数据格式的解决方案。


Tags: comidjsonmessagedomainlocalresultssender
2条回答

问题是数据不构成JSON对象,所以不能用json.loads对它们进行解码。


首先,这个看起来是一个由空格分隔的JSON对象序列。因为您不会告诉我们数据来自何处,所以这实际上只是一个有根据的猜测;希望无论文档或同事或告诉您关于这个URL的任何内容都能告诉您实际的格式。但假设我的猜测是正确的。

在Python中解析JSON对象流的最简单方法是使用raw_decode方法。像这样:*

import json

def parse_json_stream(stream):
    decoder = json.JSONDecoder()
    while stream:
        obj, idx = decoder.raw_decode(stream)
        yield obj
        stream = stream[idx:].lstrip()

但是,流中的第二个JSON对象中也有错误。看看这部分:

…
"message": "internal error,
"id": "mailerX",
…

"internal error之后缺少"。如果修复了这个问题,那么上面的函数将迭代两个JSON对象。

希望这个错误是由于您试图通过重写来手动“复制和粘贴”数据而导致的。如果是在原始源数据中,则会遇到更大的问题;您可能需要从头编写一个“断开的JSON”解析器,它可以试探性地猜测数据的目的。或者,当然,让生成源的人正确地生成它。


*一般来说,使用第二个参数raw_decode来传递开始索引,而不是每次都切掉余数的副本,会更有效。但是raw_decode不能处理前导空格。与编写跳过给定索引中空白的代码相比,切片和剥离稍微容易一些,但如果这些副本的内存和性能成本很重要,则应编写更复杂的代码。

这是因为json.load s(和json.loads)不解码多个json对象。 例如,您需要的json文件可能是: [“a”:1,“b”:2] 但是,代码的结构文件是: [“a”:1,“b”:2][“a”:1,“b”:2]

相关问题 更多 >