GVKun编程网logo

Python json.loads显示ValueError:额外数据(python json.loads报错)

7

对于想了解Pythonjson.loads显示ValueError:额外数据的读者,本文将提供新的信息,我们将详细介绍pythonjson.loads报错,并且为您提供关于json.decoder.J

对于想了解Python json.loads显示ValueError:额外数据的读者,本文将提供新的信息,我们将详细介绍python json.loads报错,并且为您提供关于json.decoder.JSONDecodeError:额外数据:第1行第5列(字符4)并引发JSONDecodeError(“ Extra data”,s,end)、json.loads是干嘛的?简单阐述json.loads python的用法、Python json.loads 显示 ValueError: Extra data、Python json.loads失败,出现“ ValueError:第1行第33列(字符33)处的无效控制字符”的有价值信息。

本文目录一览:

Python json.loads显示ValueError:额外数据(python json.loads报错)

Python json.loads显示ValueError:额外数据(python json.loads报错)

我正在从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","created_at": "Fri Jan 10 10:09:09 +0000 2014","filter_level": "medium","in_reply_to_status_id_str": null,"place": null
}

json.decoder.JSONDecodeError:额外数据:第1行第5列(字符4)并引发JSONDecodeError(“ Extra data”,s,end)

json.decoder.JSONDecodeError:额外数据:第1行第5列(字符4)并引发JSONDecodeError(“ Extra data”,s,end)

有几种方法可以从通过requests库获得的响应中解码json。

我希望您获得response的类似代码:

response = requests.get(url)

首先,它是最底层的,但可靠且易于调试,它使用response.content,它是响应的原始字节:

result = json.loads(response.content.decode('utf-8'))

second使用response.text,基本上response.contentrequests库使用最佳匹配编码自动转换为文本字符串:

result = json.loads(response.text)

以及最高级和最简单的方法,其中requests会全力做好正确的转换工作:

result = response.json()

其中一种方法应该可以使用。

此外,在收到响应后,您始终需要检查状态码,因为requests不会在非200状态码上引发异常,因此您需要在执行assert response.status_code == 200response.raise_for_status()之前解码。状态代码不等于200始终表示服务器响应错误并且响应将不包含json。这是List of HTTP Status Codes。

requests库的所有最常见功能(包括json解析)在简短的文档here中进行了描述。

json.loads是干嘛的?简单阐述json.loads python的用法

json.loads是干嘛的?简单阐述json.loads python的用法

本章节我们将为大家介绍如何使用 Python 语言来编码和解码 JSON 对象。JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写

json.loads 用于解码 JSON 数据。该函数返回 Python 字段的数据类型

语法

json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant
[, object_pairs_hook[, **kw]]]]]]]])
登录后复制
实例

以下实例展示了Python 如何解码 JSON 对象:

#!/usr/bin/python
import json

jsonData = &#39;{"a":1,"b":2,"c":3,"d":4,"e":5}&#39;;

text = json.loads(jsonData)
print text
登录后复制

以上代码执行结果为:

立即学习“Python免费学习笔记(深入)”;

{u&#39;a&#39;: 1, u&#39;c&#39;: 3, u&#39;b&#39;: 2, u&#39;e&#39;: 5, u&#39;d&#39;: 4}
登录后复制

json 类型转换到 python 的类型对照表:

json.loads.png

以上就是json.loads是干嘛的?简单阐述json.loads python的用法的详细内容,更多请关注php中文网其它相关文章!

Python json.loads 显示 ValueError: Extra data

Python json.loads 显示 ValueError: Extra data

我从 JSON 文件“new.json”中获取一些数据,我想过滤一些数据并将其存储到一个新的 JSON 文件中。这是我的代码:

import jsonwith 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.loads(and 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:\Python27\lib\json\__init__.py", line 338, in loads    return _default_decoder.decode(s)  File "C:\Python27\lib\json\decoder.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]))[{}, {}]

Python json.loads失败,出现“ ValueError:第1行第33列(字符33)处的无效控制字符”

Python json.loads失败,出现“ ValueError:第1行第33列(字符33)处的无效控制字符”

我有一个像这样的字符串:

s = u"""{"desc": "\u73cd\u54c1\u7f51-\u5168\u7403\u6f6e\u6d41\u5962\u54c1\u7f51\u7edc\u96f6\u552e\u5546 <br \/>\r\nhttp:\/\/www.zhenpin.com\/ <br \/>\r\n<br \/>\r\n200\u591a\u4e2a\u56fd\u9645\u4e00\u7ebf\u54c1\u724c\uff0c\u9876\u7ea7\u4e70\u624b\u5168\u7403\u91c7\u8d2d\uff0c100%\u6b63\u54c1\u4fdd\u969c\uff0c7\u5929\u65e0\u6761\u2026"}"""

json.loads(s) 返回如下错误消息:

ValueError: Invalid control character at: line 1 column 33 (char 33)

为什么会发生此错误?我怎么解决这个问题?

答案1

小编典典

问题是你的unicode字符串包含回车(\r)和换行符(\n
的JSON数据字符串文字。如果它们是字符串本身的一部分,则应适当地对其进行转义。如果它们不是字符串的一部分,那么它们也不应该在您的JSON中。

如果无法解决从哪里获取此JSON字符串以生成有效JSON的情况,则可以删除有问题的字符:

>>> json.loads(s.replace(''\r\n'', ''''))

或手动转义它们:

>>> json.loads(s.replace(''\r\n'', ''\\r\\n''))

我们今天的关于Python json.loads显示ValueError:额外数据python json.loads报错的分享已经告一段落,感谢您的关注,如果您想了解更多关于json.decoder.JSONDecodeError:额外数据:第1行第5列(字符4)并引发JSONDecodeError(“ Extra data”,s,end)、json.loads是干嘛的?简单阐述json.loads python的用法、Python json.loads 显示 ValueError: Extra data、Python json.loads失败,出现“ ValueError:第1行第33列(字符33)处的无效控制字符”的相关信息,请在本站查询。

本文标签: