簡體   English   中英

如何將 JSON 字符串(值中帶有雙引號)轉換為 python 字典

[英]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 文件。

正確答案——做對,GIGO 等。

堅決從源頭上解決問題。 否則你只是在堵漏水壩上的洞。 誰知道將來如果程序接收到新輸入,文本中可能會出現哪些其他特殊字符?

務實的答案——你自找的

這是一個示例 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.

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