JSON.stringify 和decodeURIComponent

以前作項目,由於組員來回的用了JSON.stringify,被看見的結果搞蒙了,今天寫這個文章,來記錄下。小程序

好比一個數組後端

var a = [{'name': 'zj', 'age': 32}]
var a1 = JSON.stringify(a)
console.log(a1)
// "[{"name":"zj","age":32}]"
// 看打印結果,第一次stringify,只是在數組兩邊用""包裹起了。
// 但若是把"[{"name":"zj","age":32}]" 賦值給某一個值,會報錯,這裏有的不理解
// Uncaught SyntaxError: Unexpected identifier

var a2 = JSON.stringify(a1)
// 第二次stringify,開始在鍵值對的非number類型上寫上\...\
console.log(a2)
// ""[{\"name\":\"zj\",\"age\":32}]""
若是要回到a初始化的狀態,執行了幾回stringify就執行幾回JSON.parse原路返回

再來看encodeURIComponent
正常狀況下,若是url上有query參數,瀏覽器可能會被默認encodeURIComponent
聽聞小程序的onload這樣的鉤子函數,會默認把url的參數decodeURIComponent(需考證),這裏能夠直接拿到onload鉤子函數裏面的query裏的鍵值對Map對象。數組

var a = [{'name': 'zj', 'age': 32}]
var a1 = JSON.stringify(a)
var a2 = encodeURIComponent(a1)
console.log(a2)
// %5B%7B%22name%22%3A%22zj%22%2C%22age%22%3A32%7D%5D
// 同理,若是再一次encodeURIComponent(a2)
// %255B%257B%2522name%2522%253A%2522zj%2522%252C%2522age%2522%253A32%257D%255D
再一次
%25255B%25257B%252522name%252522%25253A%252522zj%252522%25252C%252522age%252522%25253A32%25257D%25255D
// 若是要回到a1狀態,執行了幾回encodeURIComponent,就再執行幾回decodeURIComponent,原路返回便可

// 我瘋了嗎,若是要執行這麼屢次,由於項目就碰見,我執行了一次encodeURIComponent,但後端接收參數,也給執行了一次encodeURIComponent
但小程序的onload鉤子函數只會執行一次decodeURIComponent,因此這了還須要本身執行一次decodeURIComponent。

同理看見的stringify後的結果若是出現了\,想要回到正常的數組,至少還要執行一次JSON.parse(若是還有\,再執行一次JSON.parse 以此類推)瀏覽器

相關文章
相關標籤/搜索