Python json.loads 显示 ValueError:额外数据
- 2024-12-25 08:51:00
- admin 原创
- 140
问题描述:
我从 JSON 文件“new.json”获取了一些数据,我想过滤一些数据并将其存储到新的 JSON 文件中。这是我的代码:
import json
with open('new.json') as infile:
data = json.load(infile)
for item in data:
iden = item.get["id"]
a = item.get["a"]
b = item.get["b"]
c = item.get["c"]
if c == 'XYZ' or "XYZ" in data["text"]:
filename = 'abc.json'
try:
outfile = open(filename,'ab')
except:
outfile = open(filename,'wb')
obj_json={}
obj_json["ID"] = iden
obj_json["VAL_A"] = a
obj_json["VAL_B"] = b
我收到一个错误,回溯是:
File "rtfav.py", line 3, in <module>
data = json.load(infile)
File "/usr/lib64/python2.7/json/__init__.py", line 278, in load
**kw)
File "/usr/lib64/python2.7/json/__init__.py", line 326, in loads
return _default_decoder.decode(s)
File "/usr/lib64/python2.7/json/decoder.py", line 369, in decode
raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 88 column 2 - line 50607 column 2 (char 3077 - 1868399)
这是 new.json 中的数据示例,文件中还有大约 1500 个这样的字典
{
"contributors": null,
"truncated": false,
"text": "@HomeShop18 #DreamJob to professional rafter",
"in_reply_to_status_id": null,
"id": 421584490452893696,
"favorite_count": 0,
"source": "<a href=\"https://mobile.twitter.com\" rel=\"nofollow\">Mobile Web (M2)</a>",
"retweeted": false,
"coordinates": null,
"entities": {
"symbols": [],
"user_mentions": [
{
"id": 183093247,
"indices": [
0,
11
],
"id_str": "183093247",
"screen_name": "HomeShop18",
"name": "HomeShop18"
}
],
"hashtags": [
{
"indices": [
12,
21
],
"text": "DreamJob"
}
],
"urls": []
},
"in_reply_to_screen_name": "HomeShop18",
"id_str": "421584490452893696",
"retweet_count": 0,
"in_reply_to_user_id": 183093247,
"favorited": false,
"user": {
"follow_request_sent": null,
"profile_use_background_image": true,
"default_profile_image": false,
"id": 2254546045,
"verified": false,
"profile_image_url_https": "https://pbs.twimg.com/profile_images/413952088880594944/rcdr59OY_normal.jpeg",
"profile_sidebar_fill_color": "171106",
"profile_text_color": "8A7302",
"followers_count": 87,
"profile_sidebar_border_color": "BCB302",
"id_str": "2254546045",
"profile_background_color": "0F0A02",
"listed_count": 1,
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"utc_offset": null,
"statuses_count": 9793,
"description": "Rafter. Rafting is what I do. Me aur mera Tablet. Technocrat of Future",
"friends_count": 231,
"location": "",
"profile_link_color": "473623",
"profile_image_url": "http://pbs.twimg.com/profile_images/413952088880594944/rcdr59OY_normal.jpeg",
"following": null,
"geo_enabled": false,
"profile_banner_url": "https://pbs.twimg.com/profile_banners/2254546045/1388065343",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"name": "Jayy",
"lang": "en",
"profile_background_tile": false,
"favourites_count": 41,
"screen_name": "JzayyPsingh",
"notifications": null,
"url": null,
"created_at": "Fri Dec 20 05:46:00 +0000 2013",
"contributors_enabled": false,
"time_zone": null,
"protected": false,
"default_profile": false,
"is_translator": false
},
"geo": null,
"in_reply_to_user_id_str": "183093247",
"lang": "en",
"created_at": "Fri Jan 10 10:09:09 +0000 2014",
"filter_level": "medium",
"in_reply_to_status_id_str": null,
"place": null
}
解决方案 1:
遍历文件,在循环中将每一行加载为 JSON:
tweets = []
with open('tweets.json', 'r') as file:
for line in file:
tweets.append(json.loads(line))
这样可以避免存储中间的 Python 对象。只要每次append()
调用时都写一条完整的推文,就可以了。
解决方案 2:
正如您在以下示例中看到的,json.loads
(和json.load
) 不会解码多个 json 对象。
>>> json.loads('{}')
{}
>>> json.loads('{}{}') # == json.loads(json.dumps({}) + json.dumps({}))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:Python27libjson__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "C:Python27libjsondecoder.py", line 368, in decode
raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 1 column 3 - line 1 column 5 (char 2 - 4)
如果要转储多个字典,请将它们包装在列表中,然后转储列表(而不是多次转储字典)
>>> dict1 = {}
>>> dict2 = {}
>>> json.dumps([dict1, dict2])
'[{}, {}]'
>>> json.loads(json.dumps([dict1, dict2]))
[{}, {}]
解决方案 3:
我遇到这个问题是因为我想加载从 MongoDB 转储的 JSON 文件。它给了我一个错误
JSONDecodeError: Extra data: line 2 column 1
MongoDB JSON 转储每行有一个对象,因此对我有用的是:
import json
data = [json.loads(line) for line in open('data.json', 'r')]
解决方案 4:
我刚刚遇到了同样的错误,而我的 json 文件是这样的
{"id":"1101010","city_id":"1101","name":"TEUPAH SELATAN"}
{"id":"1101020","city_id":"1101","name":"SIMEULUE TIMUR"}
我发现它格式不正确,所以我将其更改为:
{
"datas":[
{"id":"1101010","city_id":"1101","name":"TEUPAH SELATAN"},
{"id":"1101020","city_id":"1101","name":"SIMEULUE TIMUR"}
]
}
解决方案 5:
如果您的 JSON 文件不只是 1 条 JSON 记录,也可能会发生这种情况。JSON 记录如下所示:
[{"some data": value, "next key": "another value"}]
它以方括号 [ ] 开头和结尾,方括号内是大括号 { }。可以有多对大括号,但都以右方括号 ] 结尾。如果您的 json 文件包含多个这样的大括号:
[{"some data": value, "next key": "another value"}]
[{"2nd record data": value, "2nd record key": "another value"}]
那么 loads() 将会失败。
我用我自己的失败文件验证了这一点。
import json
guestFile = open("1_guests.json",'r')
guestData = guestFile.read()
guestFile.close()
gdfJson = json.loads(guestData)
这是可行的,因为 1_guests.json 有一条记录 []。我使用的原始文件 all_guests.json 有 6 条记录,以换行符分隔。我删除了 5 条记录(我已经检查过它们被括号括起来),并以新名称保存了该文件。然后 loads 语句就起作用了。
错误是
raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 2 column 1 - line 10 column 1 (char 261900 - 6964758)
附言:我使用了“记录”这个词,但这不是正式名称。此外,如果您的文件像我的一样有换行符,您可以循环加载它,一次将一条记录加载到 json 变量中。
解决方案 6:
针对您的问题的一行代码:
data = [json.loads(line) for line in open('tweets.json', 'r')]
解决方案 7:
如果你想用两行代码解决这个问题,你可以这样做:
with open('data.json') as f:
data = [json.loads(line) for line in f]
解决方案 8:
我认为将字典保存在列表中并不是@falsetru 提出的理想解决方案。
更好的方法是,遍历字典并通过添加新行将其保存为 .json。
我们的 2 本词典是
d1 = {'a':1}
d2 = {'b':2}
你可以将它们写入 .json
import json
with open('sample.json','a') as sample:
for dict in [d1,d2]:
sample.write('{}
'.format(json.dumps(dict)))
你可以毫无问题地读取 json 文件
with open('sample.json','r') as sample:
for line in sample:
line = json.loads(line.strip())
簡單高效
解决方案 9:
我的 json 文件的格式与问题中的格式完全相同,但这里的解决方案都不起作用。最后,我在另一个 Stackoverflow 线程上找到了一种解决方法。由于这篇文章是 Google 搜索中的第一个链接,因此我将该答案放在这里,以便将来其他人访问这篇文章时可以更轻松地找到它。
正如上面所说,有效的 json 文件需要在开头有“[”,在结尾有“]”。此外,每个 json 项后面必须有“},”,而不是“}”。所有括号都没有引号!这段代码只是将格式错误的 json 文件修改为正确的格式。
https://stackoverflow.com/a/51919788/2772087
解决方案 10:
`如果您使用
read()文件描述符的方法,则错误是由于符号引起的...所以**不要**使用 & co 来绕过问题
readlines()`,而只需删除这样的字符!
import json
path = # contains for example {"c": 4} also on multy-lines
new_d = {'new': 5}
with open(path, 'r') as fd:
d_old_str = fd.read().replace('
', '') # remove all
old_d = json.loads(d_old_str)
# update new_d (python3.9 otherwise new_d.update(old_d))
new_d |= old_d
with open(path2, 'w') as fd:
fd.write(json.dumps(new_d)) # save the dictionary to file (in case needed)
...如果你真的想readlines()
在这里使用替代解决方案
new_d = {'new': 5}
with open('some_path', 'r') as fd:
d_old_str = ''.join(fd.readlines()) # concatenate the lines
d_old = json.loads(d_old_str)
# then as above
解决方案 11:
如果您的数据来自您无法控制的来源,请使用此
def load_multi_json(line: str) -> [dict]:
"""
Fix some files with multiple objects on one line
"""
try:
return [json.loads(line)]
except JSONDecodeError as err:
if err.msg == 'Extra data':
head = [json.loads(line[0:err.pos])]
tail = FrontFile.load_multi_json(line[err.pos:])
return head + tail
else:
raise err
解决方案 12:
如果您的文档(文件、字符串等)包含多个未分隔的 json 对象(例如,它们之间没有换行符),则可以使用 json.JSONDecoder().raw_decode()。这将返回解析结束的位置,因此您可以从该点开始再次调用它。它不会引发额外数据错误。