基本上我正在使用一個字串,它是 python 中的 json 字串,但是當在 javascript 中使用時,它有“'”標簽而不是雙引號,我想把它變成一個真正的 json(通過使用 JSON.parse() ) 但是句子中間有一些引號(因為我把“'”換成了雙引號)。
示例:'{"author":"Jonah D"Almeida", ... }'(我想替換 D 和 Almeida 之間的那個)
由于整個句子周圍已經有引號,javascript給出了一個錯誤,因為它無法從中創建一個json,所以,為了解決這個問題,基本上我想將句子中間的引號替換為'(單標記),但前提是它在引號之前和之后都有字母。
我的想法: myString.replace('letter before ... " ... letter after', "'")
知道我怎樣才能得到正確的表達嗎?基本上我只想知道正則運算式檢查“參考前后是否有字母,如果是,請將其更改為單標記(')。
uj5u.com熱心網友回復:
OP ... “基本上我正在使用一個 json 字串的字串”
上面的示例不是 OP 所指的json string。OP 的示例資料字串已經是無效的 JSON。
因此,第一件事是修復生成此類資料的程序。
因為 ...
“決議有效的JSON 資料將回傳一個完全有效的物件,如果是 OP 的用例,也會回傳一個正確轉義的字串值。”
... 證明 ...
const testSample_A = { author: "Jonah D'Almeida" };
const testSample_B = { author: 'Jonah D"Almeida' };
const testSample_C = { author: 'Jonah D\'Almeida' };
const testSample_D = { author: "Jonah D\"Almeida" };
console.log({
testSample_A,
testSample_B,
testSample_C,
testSample_D,
});
console.log('JSON.stringify(...) ... ', {
testSample_A: JSON.stringify(testSample_A),
testSample_B: JSON.stringify(testSample_B),
testSample_C: JSON.stringify(testSample_C),
testSample_D: JSON.stringify(testSample_D),
});
console.log('JSON.parse(JSON.stringify(...)) ... ', {
testSample_A: JSON.parse(JSON.stringify(testSample_A)),
testSample_B: JSON.parse(JSON.stringify(testSample_B)),
testSample_C: JSON.parse(JSON.stringify(testSample_C)),
testSample_D: JSON.parse(JSON.stringify(testSample_D)),
});
.as-console-wrapper { min-height: 100%!important; top: 0; }
編輯
盡管如此,仍然可以基于正則運算式來實作完全符合 OP 要求的清理任務,該正則運算式具有積極的前瞻和積極的后瞻功能……僅適用于基本拉丁語/(?<=\w)"(?=\w)/gm或更多具有unicode 轉義的國際.../(?<=\p{L})"(?=\p{L})/gmu
console.log('Letter unicode escapes ...', `
{"author": "Jonah D"Almeida", ... }
{"author": "Jon"ah D"Almeida", ... }
{"author": "Jon"ah D"Alme"ida", ... }`
.replace(/(?<=\p{L})"(?=\p{L})/gmu, '\\"')
);
console.log('Basic Latin support ...', `
{"author": "Jonah D"Almeida", ... }
{"author": "Jon"ah D"Almeida", ... }
{"author": "Jon"ah D"Alme"ida", ... }`
.replace(/(?<=\w)"(?=\w)/gm, '\\"')
);
console.log(
'sanitized and parsed string data ...',
JSON.parse(`[
{ "author": "Jonah D"Almeida" },
{ "author": "Jon"ah D"Almeida" },
{ "author": "Jon"ah D"Alme"ida" }
]`.replace(/(?<=\p{L})"(?=\p{L})/gmu, '\\"'))
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/408160.html
標籤:
