[英]convert “converted” object string to JSON or Object
我遇到了以下問題,因為我升級了我的prototypeJS框架。
JSON 解析無法再將此字符串轉換為對象。
"{empty: false, ip: true}"
以前在 1.6 版中是可能的,現在它需要是一個“經過驗證的”JSON 字符串,例如
'{"empty": false, "ip": true}'
但是如何將第一個示例轉換回對象?
JSON 需要引用所有鍵,因此:
"{empty: false, ip: true}"
不是有效的 JSON。 您需要對其進行預處理才能解析此 JSON。
function preprocessJSON(str) {
return str.replace(/("(\\.|[^"])*"|'(\\.|[^'])*')|(\w+)\s*:/g,
function(all, string, strDouble, strSingle, jsonLabel) {
if (jsonLabel) {
return '"' + jsonLabel + '": ';
}
return all;
});
}
(在 JSFiddle 上試試)它使用一個簡單的正則表達式來替換一個單詞,后跟冒號,該單詞用雙引號引用。 正則表達式不會引用其他字符串中的標簽。
然后你就可以安全的
data = JSON.parse(preprocessJSON(json));
const dataWithQuotes = str.replace(/("(\\.|[^"])*"|'(\\.|[^'])*')|(\w+)\s*:/g, (all, string, strDouble, strSingle, jsonLabel) => {
if (jsonLabel) {
return `"${jsonLabel}": `;
}
return all;
});
return dataWithQuotes
與上述類似的解決方案,但使用箭頭函數進行了更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.