Python json.loads失败,出现"ValueError:第1行第33列(字符33)处的无效控制字符" [英] Python json.loads fails with `ValueError: Invalid control character at: line 1 column 33 (char 33)`

查看:123
本文介绍了Python json.loads失败,出现"ValueError:第1行第33列(字符33)处的无效控制字符"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a string like this:

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)

为什么会出现此错误?我该如何解决这个问题?

Why does this error occur? How can I solve this problem?

推荐答案

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

The problem is your unicode string contains carriage returns (\r) and newlines (\n) within a string literal in the JSON data. If they were meant to be part of the string itself, they should be escaped appropriately. If they weren't meant to be part of the string, they shouldn't be in your JSON either.

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

If you can't fix where you got this JSON string to produce valid JSON, you could either remove the offending characters:

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

或手动进行转义:

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

这篇关于Python json.loads失败,出现"ValueError:第1行第33列(字符33)处的无效控制字符"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆