我正在尝试编写将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\":\"150544082@N05\",\"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": "61623564@N06", "secret": "97e4f3a4a2", "server": "4255", "farm": 5, "title": "IMG_9105", "ispublic": 1, "isfriend": 0, "isfamily": 0}, {"id": "35678623895", "owner": "61623564@N06", "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 :(得分:0)
在转储尝试加载之前
cache_file.write(json.dumps(json.loads(CACHE_DICTION)))