问题描述
读取数据时使用 json.load 从 JSON 文件加载数据时,您可能会遇到“ValueError: Extra data”错误。这表明 JSON 文件中除了有效的 JSON 数据之外还有其他尾随内容。
示例数据
以下是“新文件”中的数据示例.json”文件,这会导致错误:
{ "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 }
解决方案
发生错误是因为 json.load 尝试将整个文件解析为单个 JSON 对象。但是,该文件包含多行,每行代表一个单独的 JSON 对象。
要解决此问题,请按照以下步骤操作:
tweets = [] with open('new.json') as infile: for line in infile: tweets.append(json.loads(line))
通过避免中间 Python 对象并确保仅附加完整的推文,此方法可以防止内存过载并允许您处理大型 JSON高效地归档。
以上是在 Python 中使用 json.loads 时,为什么会收到'ValueError: Extra Data”?的详细内容。更多信息请关注PHP中文网其他相关文章!