[英]Python how convert single quotes to double quotes to format as json string
[英]How to convert JSON string (with double quotes in its values) to python dictionary
我有一些這樣的 JSON 文件:
{
"@context": "http://schema.org",
"@type": "Product",
"name": "ADIZERO ADIOS PRO 2 Löparskor",
"@id": "adidas-adizero-adios-pro-2-loparskor",
"color": "Lila",
"description": "Example text "Best Comfort" an other example text.",
"brand": {
"@type": "Thing",
"name": "adidas"
},
"audience": {
"@type": "Audience",
"name": "Herr, Dam"
}
}
我知道它不是有效的 JSON 文件,因為在描述字段中有" "
但我如何使用 python 操作此字符串並使用json.loads()
我正在考慮一些正則表達式來刪除這些內部雙引號,這可能嗎?
順便說一句:不可能操作源 JSON 文件。
堅決從源頭上解決問題。 否則你只是在堵漏水壩上的洞。 誰知道將來如果程序接收到新輸入,文本中可能會出現哪些其他特殊字符?
這是一個示例 Python 腳本,它在 stdin 上采用“錯誤的 JSON”並在 stdout 上生成(希望)有效的 JSON output:
import sys
import re
def main():
for line in sys.stdin:
# Replace content where the property value has invalid
# double quotes that were supposed to be part of the string
# with properly quoted double quotes.
line = re.sub(r'(: ")(.*)(",)$', replacer, line)
sys.stdout.write(line)
def replacer(match):
before = match.group(1)
string_to_fix = match.group(2)
after = match.group(3)
return before + escape_quotes(string_to_fix) + after
def replacer2(match):
return match.group(1) + match.group(2).upper() + match.group(3)
def escape_quotes(s):
return s.replace('\\', '\\\\').replace('"', '\\"')
main()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.