簡體   English   中英

如何用 ' 替換替換 \\"

[英]How can I replace replace \" with '

我有以下內容:

{

"z":"[{\"ItemId\":\"1234\",\"a\":\"1234\",\"b\":\"4567\",\"c\":\"d\"}]"

}

這是我從某個 API 獲得的 json 響應的一部分。 我需要用' s 替換\\" s。不幸的是,這就是我卡住的地方!

我得到的大多數答案只是簡單地用""" "替換\\ ,所以這對我沒有幫助。 所以我的問題如下:

如何用'替換\\"

  1. 在我復制粘貼內容的文件中?
  2. 如果我收到此作為對某個 API 調用的響應?

我嘗試了以下方法來替換文件中的內容,但顯然我只是將" s 替換為'

  with open(file, "r") as f:
    content = f.read()
    new_content = content.replace("\"", "'")
    with open(file, "w") as new_file:
        new_file.write(new_content)

如果您要做的是將每個值從 JSON 字符串轉換為 Python repr() 字符串,同時將包裝器格式保留為 JSON,則可能如下所示:

with open(filename, "r") as old_file:
  old_content = json.load(old_file)
  new_content = {k: repr(json.loads(v)) for k, v in old_content.items()}
  with open(filename, "w") as new_file:
    json.dump(new_content, new_file)

如果您的舊文件包含:

{"z":"[{\"ItemId\":\"1234\",\"a\":\"1234\",\"b\":\"4567\",\"c\":\"d\"}]"}

...新文件將包含:

{"z": "[{'ItemId': '1234', 'a': '1234', 'b': '4567', 'c': 'd'}]"}

請注意,在這個新文件中,內部字段現在是 Python 格式,而不是 JSON 格式; 它們不能再被 JSON 解析器解析。 通常,我會建議做一些不同的事情,例如:

with open(filename, "r") as old_file:
  old_content = json.load(old_file)
  new_content = {k: json.loads(v) for k, v in old_content.items()}
  with open(filename, "w") as new_file:
    json.dump(new_content, new_file)

...這將產生一個輸出文件:

{"z": [{"ItemId": "1234", "a": "1234", "b": "4567", "c": "d"}]}

...使用標准的以 JSON 為中心的工具( jq等)既易於閱讀又易於處理。

使用json模塊,您可以轉儲數據,然后使用以下命令加載它:

import json

data = {

    "z": "[{\"ItemId\":\"1234\",\"a\":\"1234\",\"b\":\"4567\",\"c\":\"d\"}]"

}


g = json.dumps(data)

c = json.loads(data)

print(c)

print(str(c).replace("\"","'"))

輸出:

{'z': '[{"ItemId":"1234","a":"1234","b":"4567","c":"d"}]'}

{'z': '[{'ItemId':'1234','a':'1234','b':'4567','c':'d'}]'}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM