ValueError:额外数据:加载JSON时

时间:2014-03-01 09:18:54

标签: python json

我在加载JSON时遇到问题。

response = conn.getresponse()
data = response.read().decode('utf-8')
print ("raw data >> ", data)
data1 = json.loads(data)
print (data1)

给了我一个错误:

raw data >>  {"Len":"0000000000000376"}{"PipeType":2,"Content":{"ActionType":1,"Data":{"UserID":12,"RoomID":1,"UserData":{"NickName":"Koko","MoreAboutMe":null,"Age":21,"Man":false,"Area":9,"HaveCam":false,"isOldPoll":false,"LoginTime":635292689335460656,"RoomEnter":635292689335460656,"FacebookId":null,"Email":null,"FirstName":null,"LastName":null,"BirthDate":null,"FacebookLink":null,"Rank":-1}}}}{"Len":"0000000000000159"}{"PipeType":2,"Content":{"ActionType":3,"Data":{"Message":"no matter","ColorID":0,"UserID":13,"UserNick":"Jovani","SentDate":null,"Rank":null}}}
Exception in Tkinter callback
...
ValueError: Extra data: line 1 column 26 - line 1 column 587 (char 26 - 587)

有什么想法吗?

由于

1 个答案:

答案 0 :(得分:6)

json.loads不处理多个json数据。

以下是解决方法。

import json
import re

nonspace = re.compile(r'\S')
def iterparse(j):
    decoder = json.JSONDecoder()
    pos = 0
    while True:
        matched = nonspace.search(j, pos)
        if not matched:
            break
        pos = matched.start()
        decoded, pos = decoder.raw_decode(j, pos)
        yield decoded

rawdata = '{"Len":"0000000000000376"}{"PipeType":2}'
for decoded in iterparse(rawdata):
    print(decoded)

输出:

{u'Len': u'0000000000000376'}
{u'PipeType': 2}