[英]newline causes SyntaxError: EOL while scanning string literal
An ipad application sends this json to me and I read it by request.POST.get and then pars it by ast.literal_eval 一个ipad应用程序将此json发送给我,我通过request.POST.get读取了它,然后通过ast.literal_eval对其进行了解析
u'[\n {\n "type" : 2,\n "dateCreated" : "Wed, 24 Apr 2013 17:20:50 0100",\n "dateStart" : "Wed, 24 Apr 2013 18:00:00 0100",\n "appointmentId" : 0,\n "withP" : [\n\n ],\n "seenTime" : null,\n "ofCWithId" : 2,\n "ofClientWithId" : 68,\n "dateEnd" : "Wed, 24 Apr 2013 19:00:00 0100",\n "comments" : "Test test test\n.\n( ) \'\' test \'\' \' test \'\n",\n "inLocation" : null,\n ...bla bla bla...]'
I get this error: 我收到此错误:
'comments' : 'Test test test
^
SyntaxError: EOL while scanning string literal
I can understand that newline character is the problem but I don't know how to solve it. 我可以理解换行符是问题所在,但我不知道如何解决。 I'm using django 1.4.2 python 2.7.3
我正在使用Django 1.4.2 python 2.7.3
I really appreciate your help 非常感谢您的帮助
Try to add \\'\\'\\' at the beginning of the string and at the end. 尝试在字符串的开头和结尾添加\\'\\'\\'。
Like this: 像这样:
u'\'\'\'[\n ... bla bla bla...]\'\'\''
You shouldn't use ast.literal_eval to read JSON. 您不应该使用ast.literal_eval来读取JSON。 For reading JSON there is a separate module called
json
. 为了读取JSON,有一个名为
json
的单独模块 。
Load JSON data using it: 使用它加载JSON数据:
import json
data = """{"type":null,"dateCreated":"Wed, 24 Apr 2013 17:20:50 0100"}"""
json_data = json.loads(data)
ast.literal_eval was made to evaluate Python code that is represented as a string. ast.literal_eval用于评估以字符串形式表示的Python代码。 It wasn't designed to work with JSON data.
它并非旨在用于JSON数据。
null
in JSON is None
in Python Dictionary, as an example of a difference. JSON的
null
在Python字典中为None
,这是一个差异示例。
Another reason you get an error is because JSON you try to parse is invalid . 出现错误的另一个原因是,您尝试解析的JSON 无效 。 It looks like there's a server side problem or there is a problem with the way you get your JSON data from the server.
看来有服务器端问题,或者从服务器获取JSON数据的方式有问题。
Newline symbols ( \\n
) should be escaped within a string. 换行符号(
\\n
)应该在字符串中转义。 Also, '
shouldn't be escaped, according to JSON specs . 另外,根据JSON规范 ,
'
不应转义。 Alternatively, you can use strict=False
argument with json.loads
to allow control characters inside strings. 另外,您可以在
json.loads
使用strict=False
参数,以允许字符串中包含控制字符。
Valid JSON from your example would look like this: 您的示例中的有效JSON如下所示:
{
"type": 2,
"dateCreated": "Wed, 24 Apr 2013 17:20:50 0100",
"dateStart": "Wed, 24 Apr 2013 18:00:00 0100",
"appointmentId": 0,
"withP": ["\\n\\n"],
"seenTime": null,
"ofCWithId": 2,
"ofClientWithId": 68,
"dateEnd": "Wed, 24 Apr 2013 19:00:00 0100",
"comments": "Test test test\\n.\\n( ) '' test '' ' test '\\n",
"inLocation": null
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.