# 2. 透過 JSON.parse、JSON.stringify 來編譯資料 - 假設來講,我們有一筆陣列資料: 而今天我們想透過 localstorage 來存取這筆資料 ``` var country = [ { farmer: '卡斯柏', } ]; localStorage.setItem('countryItem', country); ``` - 看起來沒什麼問題吧?這樣的寫法,來看看會發生什麼事情: 透過圖片可以發現, key 是 countryItem 沒問題,可是呢: value 居然不是正常的陣列資料,而是 `[object][object]` ![](https://i.imgur.com/risQPWW.png) - 這就非常有事了,該如何解決呢? ### 1. 透過 localstorage setItem 存取資料,資料型別會自動變成 string: - 也就是說,雖然我們本身的資料設定是一組陣列,但因為存到了 localstorage 使得 array 變成了 string 這也是為何資料在 application 會顯示 object object 這種奇怪的內容根本原因 ``` localStorage.setItem('countryItem', country); // 宣告 getData 為 getItem,並且使用 console.log / typeof 查詢 getData: var getData = localStorage.getItem('countryItem'); console.log(typeof (getData)); // 獲得 string 這個答案 ``` --- ### 2. 如何將 localstorage 由字串轉換成 array ? - JSON.stringify() 1. setItem 撰寫方式不變,唯一不同的地方則是: 記得丟入 value,請使用**已經字串化的變數** ``` // setItem 字串化: var countryString = JSON.stringify(country); localStorage.setItem('countryItem', countryString); ``` 2. 回到瀏覽器就可以發現原本的 object object 乖乖地轉換成 array 哩: ![](https://i.imgur.com/IAruLIB.png) --- ### 3. getItem 字串化的內容試試看: ``` var getData = localStorage.getItem('countryItem'); console.log(getData); // [{"farmer":"查理"}] - 格式為 string,這無法被當作陣列來使用 ``` - 請特別注意,任何儲存到 localStorage 的資料,一律都會是 **string**。 - 故任何 array 資料若要存到 localstorage,除了要先存成 string 被解析之外,透過getItem 撈取資料時,還需要再一次經過 parse 編譯過: ### 4. JSON.Parse(): - 將還是字串的 getItem 內容轉換成 array,並且可以正常使用陣列資料 ``` // parse getIem: var getDataAry = JSON.parse(getData); console.log(typeof (getDataAry)); ``` ``` // 撈取資料測試: console.log(getDataAry[0].farmer); // 查理 ``` ###### tags: `JavaScript - localStorage`