简体   繁体   English

从 json 文件中删除反斜杠

[英]Removing Backslash from a json file

I have a URL that generates a json file when called.我有一个 URL,它在调用时生成一个 json 文件。 The file is dynamic so the contents change with time.该文件是动态的,因此内容会随时间而变化。 I wrote a code to retrieve the file as follows:我写了一段代码来检索文件,如下所示:

page = requests.get(URL)
page1=''
page1='\''+page.text+'\''
page1=page1.replace("\\\"", "\"")
page1=page1.translate({ord('\\'):None})
page1=page1.translate({ord(c): "" for c in "\\"})

with open(FileName, "w") as FileContent:
    json.dump(page1, FileContent)
    FileContent.close()

The problem is the file has \" where ever it is supposed to contain " only (when opened in a json viewer) and i have to remove \ manually for the json to work.问题是文件只有\"它应该包含"的地方(当在 json 查看器中打开时),我必须手动删除\才能使 json 工作。 And the above coding don't seem to work.而且上面的编码似乎不起作用。 How do we implement this and what is wrong in all the above efforts here?我们如何实施这一点以及上述所有努力有什么问题?

If page.text is JSON, you don't need to do any of this manipulation, just write it to the file.如果page.text是 JSON,则无需进行任何操作,只需将其写入文件即可。

page = requests.get(URL)
with open(FileName, "w") as FileContent:
    FileContent.write(page.text)

Also, you don't need to use close() when you use with open() .此外, with open()使用时不需要使用close() ) 。 The context manager automatically closes it.上下文管理器自动关闭它。

requests.get() returns a response object requests.get()返回响应 object

If your server returns some body that is JSON, then rather than using .text , you should use .json()如果您的服务器返回一些主体是 JSON,那么您应该使用.json()而不是使用.text

And then, you don't need to escape/replace anything, just dump that to a file as-is然后,您无需转义/替换任何内容,只需按原样将其转储到文件中

import requests

page = requests.get(URL)
if page.status_code // 100 == 2:
  with open(FileName, "w") as f:
    f.write(page.json())

If your server returns escaped JSON text, then you should fix it there , not in the client如果您的服务器返回转义的 JSON 文本,那么您应该在那里修复它,而不是在客户端中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM