我正在使用以下函数从flickr json
获取API
。它返回的字符串是一个格式正确的JSON块:
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)
CACHE_DICTION[request_data] = response.text[14:-1]
cache_file = open(CACHE_FNAME, 'w')
cache_file.write(json.dumps(CACHE_DICTION))
cache_file.close()
return response.text[14:-1]
我遇到的问题是,当我将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\",\"location\":\"Cincinnati, USA\",\"iconserver\":\"4236\",\"iconfarm\":5,\"path_alias\":\"ankitrana_\"},\"title\":{\"_content\":\"7\"},\"description\":{\"_content\":\"\"},\"visibility\":{\"ispublic\":1,\"isfriend\":0,\"isfamily\":0},\"dates\":{\"posted\":\"1499030213\",\"taken\":\"2017-06-19 13:43:38\",\"takengranularity\":\"0\",\"takenunknown\":\"0\",\"lastupdate\":\"1499041020\"},\"views\":\"41\",\"editability\":{\"cancomment\":0,\"canaddmeta\":0},\"publiceditability\":{\"cancomment\":1,\"canaddmeta\":0},\"usage\":{\"candownload\":1,\"canblog\":0,\"canprint\":0,\"canshare\":1},\"comments\":{\"_content\":\"0\"},\"notes\":{\"note\":[]},\"people\":{\"haspeople\":0},\"tags\":{\"tag\":[{\"id\":\"150538742-34869402493-5630\",\"author\":\"150544082@N05\",\"authorname\":\"ankitrana_\",\"raw\":\"cincinnati\",\"_content\":\"cincinnati\",\"machine_tag\":0},{\"id\":\"150538742-34869402493-226\",\"author\":\"150544082@N05\",\"authorname\":\"ankitrana_\",\"raw\":\"ohio\",\"_content\":\"ohio\",\"machine_tag\":false},
... etc., etc.}
如何在没有这些额外的\
字符的情况下将JSON存储到现有文件中,因为在打印字符串时会显示它?
答案 0 :(得分:1)
使用your_string.decode('string_escape')
将\"
转换为"
更新:
您的字符串已转义,因为json.dumps()
,它将对象转换为字符串,之后您可以使用json.loads()
读取它,结果未转义。
您可以使用str()
cache_file.write(str(CACHE_DICTION))
# {'myparam' :'"162000","photo":...'
但问题是用单引号保存到文件,它不是有效的json而且与json.loads()
不兼容
我的建议保留您的代码,除非您想将其存储到文件CACHE_FNAME.json
cache_file = open(CACHE_FNAME, 'w')
cache_file.write(response.text)
cache_file.close()
# {"photos":{"page":1,"pages":6478,..}
答案 1 :(得分:0)
你可以尝试用python
中的str.replace函数替换“\”在以下行
之后添加代码cache_file = open(CACHE_FNAME,'w')
json_item = str(json.dumps(CACHE_DICTION))
json_item.replace("\", "")
并更改此行
cache_file.write(json.dumps(CACHE_DICTION))
到
cache_file.write(json_item)
让我知道这是否适合您
答案 2 :(得分:0)
只需用空格替换\
即可。
我在使用JSON时做了同样的事情。
json_new = json.replace('\\', '')