我遇到了一個非常奇怪的錯誤。如果我運行JSON.Parse('[""d""]'),那么我有錯誤。"在JSON的第3個位置出現了意外的token d"
。 。JSON.parse(' ["d"]'/span>)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
如果我運行 console.log(JSON.stringify(['"d"')),那么我得到'[""d""]'
。console. log(JSON.stringify(['"d"])
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
如果我運行 console.log(JSON.parse(JSON.stringify(['"d"'))),那么我得到好的結果 [""d""]
。 。console.log(JSON。 parse(JSON.stringify(['"d"]))
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
如果我使用eval函式,那么我有錯誤。"未發現的語法錯誤。
var someJson=JSON. stringify(['"d"'/span>])。
window.eval(`JSON.parse('${someJson}')`/code>
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
如何解決這個問題?
我使用了一些外部庫。
我使用一些外部庫,有window.eval(JSON.parse('${JSON.stringify(t)}')/code>)。其中t--帶有字串的json陣列。字串可以包含雙引號。它拋出了例外。
我發現js改變了我的字串值,當我設定它時。
。var someJson='["d"]'。
console.log(someJson);
<iframe name="sif5" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
它回傳'[""d""],當我運行JSON.Parse時,它是不正確的JSON。
如何修復它?
uj5u.com熱心網友回復:
JSON.parse(' ["d"] ')
是JS字串中的一個特殊字符,所以要在你的JSON中包含它,你需要轉義它。
const yourString = '["d">';
const validJSON = '[""d"]'
const parsedData = JSON.parse(validJSON)。
document.querySelector('#yourString').value = yourString;
document.querySelector('#validJSON').value = validJSON;
<p>/span>你的字串。<output id="ourString"> </output>>
<p>/span>有效的JSON。<output id="validJSON"/span>> </output>
<iframe name="sif6" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
根據經驗,在字串字面中嵌入JSON是浪費時間和精力的。你可以直接撰寫你從決議JSON中得到的JS資料結構。
uj5u.com熱心網友回復:
@Quentin 非常感謝你的想法! 結果回答我:
。var someJson=JSON. stringify(['"d"'/span>])。
console.log(window.eval(`JSON. parse('${someJson.replaceAll('/span>,'/span>)}'))
<iframe name="sif7" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/329430.html
標籤:
