This question already has answers here:
JSON formatting adding \ characters when I append file, but not to string in output

(3个答案)


2年前关闭。





我正在尝试编写将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方法中的编码引入的,因为即使我删除了\,它们仍然保留在写入文件中。

最佳答案

在转储之前尝试加载它

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

10-08 02:21