在解析Python中的JSON響應時出現錯誤。例如:用Python解析JSON
{
"oneliners": [
"she\'s the one",
"who opened the gates"
]
}
JSON解碼器在單引號無效轉義時咳嗽起來。通常,在解碼可能包含無效轉義的響應之前,人們是否應用REGEX刪除轉義斜槓字符?
在解析Python中的JSON響應時出現錯誤。例如:用Python解析JSON
{
"oneliners": [
"she\'s the one",
"who opened the gates"
]
}
JSON解碼器在單引號無效轉義時咳嗽起來。通常,在解碼可能包含無效轉義的響應之前,人們是否應用REGEX刪除轉義斜槓字符?
Pyparsing附帶了一個JSON解析例子(或者你可以得到它的在線here):
>>> text = r"""{
... "oneliners": [
... "she\'s the one",
... "who opened the gates"
... ]
... } """
>>> text
'{ \n "oneliners": [ \n "she\\\'s the one", \n "who opened the gates" \n ] \n} '
>>> obj = jsonObject.parseString(text)
>>> obj.asList()
[['oneliners', ["she\\'s the one", 'who opened the gates']]]
>>> obj.asDict()
{'oneliners': (["she\\'s the one", 'who opened the gates'], {})}
>>> obj.oneliners
(["she\\'s the one", 'who opened the gates'], {})
>>> obj.oneliners.asList()
["she\\'s the one", 'who opened the gates']
不要被表面上的包含一個字典的(在「{}」)在obj.oneliners
被推遲,這只是pyparsing ParseResults對象的repr輸出。您可以像處理普通列表一樣處理obj.oneliners,或者如果您喜歡,可以使用asList
(如圖所示)將其內容作爲列表提取。
import json
s = """{
"oneliners": [
"she\'s the one",
"who opened the gates"
]
}"""
print "%r" % json.loads(s)
這似乎在Python 2.6及更高版本中工作得很好。
必須使用原始字符串定義s,否則json.loads將永遠不會看到'\'。 (而且我不是那種低估了你的人。) – PaulMcG 2010-07-01 13:01:22
可能已經發誓說我試過了字符串的原始版本,我很抱歉,多麼可怕的第一篇文章。 – StormyDragon 2010-07-02 09:55:43
如果您在您的JSON字符串表示中有\'
字符序列,並且您知道它應該是'
,則表示它之前未正確地轉義,您應該在那裏解決問題。
如果您不能,您應該在向JSON解析器提供這樣的字符串之前進行替換。 simplejson
將無法解析它,cjson
或anyjson
不會失敗,但會從字面上處理它,所以您將在結果數據中使用反斜槓撇號序列。
您使用的是哪種JSON解碼器? – sdolan 2010-07-01 07:28:41
@sdolan:任何* strict * JSON解碼器(例如simplejson - http://pypi.python.org/pypi/simplejson/)都會窒息,它確實是JSON中的無效轉義(與JavaScript相反): http://json.org – 2010-07-01 07:30:47
@TJ Crowder:感謝您的澄清。 – sdolan 2010-07-01 07:57:03