2017-08-07 82 views
0

我正在嘗試編寫將JSON寫入文件而不包含用於轉義引號的反斜槓的代碼。目前我的輸出是這樣的:將JSON寫入文件而無需將轉義反斜槓寫入文件?

"https://api.flickr.com/services/rest/format-json_method-flickr.photos.getInfo_photo_id-34869402493": "{\"photo\":{\"id\":\"34869402493\",\"secret\":\"56fcf0342c\",\"server\":\"4057\",\"farm\":5,\"dateuploaded\":\"1499030213\",\"isfavorite\":0,\"license\":\"0\",\"safety_level\":\"0\",\"rotation\":0,\"originalsecret\":\"c4d1d316ed\",\"originalformat\":\"jpg\",\"owner\":{\"nsid\":\"[email protected]\",\"username\":\"ankitrana_\",\"realname\":\"Ankit Rana\",... 

這裏是我的目標爲:

{"https://api.flickr.com/services/rest/format-json_method-flickr.photos.search_per_page-50_tag_mode-all_tags-mountains": {"photos": {"page": 1, "pages": 5023, "perpage": 50, "total": "251136", "photo": [{"id": "35678630595", "owner": "[email protected]", "secret": "97e4f3a4a2", "server": "4255", "farm": 5, "title": "IMG_9105", "ispublic": 1, "isfriend": 0, "isfamily": 0}, {"id": "35678623895", "owner": "[email protected]", "secret": "f24e2ebb04", "server": "4003", "farm": 5, "title": "IMG_9247", "ispublic": 1, "isfriend": 0, "isfamily": 0}, 

這是因爲我有它的那一刻編寫的功能:

def get_photo_data(photo_id): 
para = {} 
para["photo_id"] = photo_id 
para["method"] = "flickr.photos.getInfo" 
para["format"] = "json" 
para["api_key"] = FLICKR_KEY 
request_data = params_unique_combination("https://api.flickr.com/services/rest/", para) 

if request_data in CACHE_DICTION: 
    return CACHE_DICTION[request_data] 
else: 
    response = requests.get("https://api.flickr.com/services/rest/", para) 
    jstring = response.text[14:-1] 
    CACHE_DICTION[request_data] = jstring.replace(r'\"','"') 
    cache_file = open(CACHE_FNAME, 'w') 
    cache_file.write(json.dumps(CACHE_DICTION)) 
    cache_file.close() 
    return CACHE_DICTION[request_data] 

我相信問題是通過在.dumps方法中完成的編碼引入的,因爲即使我刪除了\,它們仍保留在寫入文件中。

回答

0

傾銷之前試圖加載它

cache_file.write(json.dumps(json.loads(CACHE_DICTION)))