2012-08-09 79 views
2

我訪問一個如下返回JSON服務逃脫JSON中的URL字符串在一個鍵值對中。處理使用python

所以,從本質上來說,在我的腳本完成了json的處理之後,它會以某種分隔的方式在文件中輸出url和somefile。

已處理的文件後,該輸出上面提供的JSON是:

url: http://someurl:someport/somefolder/somefile 
file: somefile 

我敢肯定在Python衆多JSON解析器將解析JSON,但我會如何處理URL字符串已經使用轉義字符進行了預處理?我是否需要編寫自己的url編碼器,將脫離url字符串中的轉義字符?

此外,我需要標記化URL的各個組件到達'文件'部分,有沒有任何庫可以幫助你呢?

感謝

+1

喜歡的東西http://stackoverflow.com/questions/1885181/how-do-i-un-escape- a-backslash-escaped-string-in-python會有幫助嗎? – favoretti 2012-08-09 21:28:53

+0

看來,特定的事情沒有幫助,但我偶然發現了其他事情。 http://www.quora.com/Why-does-the-cjson-Python-module-not-correctly-unescape-reverse-solidus-solidus – favoretti 2012-08-09 21:32:29

回答

2

你們的榜樣JSON不需要 「c_url」 K-V對後面的逗號。

>>> import json 
>>> st = '{"A":"A value","B":{ "B1":"B1 value", "B2":"B2 value" },"C":{ "c 
_url":"http:\/\/someurl:someport\/somefolder\/somefile" }}' 
>>> json.loads(st) 
{u'A': u'A value', u'C': {u'c_url': u'http://someurl:someport/somefolder/somefile'}, u'B': {u'B1': u 
'B1 value', u'B2': u'B2 value'}} 

而得到URL的只是 'somefile' 部分:

url.split('/')[url.count('/')] 
3

所以,按照http://www.quora.com/Why-does-the-cjson-Python-module-not-correctly-unescape-reverse-solidus-solidus

simplejson應該能夠處理這個 「越野車」 逃逸算法。試想一下:

#!/usr/bin/env python 
import simplejson 

print simplejson.loads('"http:\/\/someurl:someport\/somefolder\/somefile"') 

注意,這simplejson是不是一個標準的包裝,而是通過easy_install安裝。

輸出示例:

[85][23:35:24] [email protected] (~/tests) > python unescape.py 
http://someurl:someport/somefolder/somefile