简体   繁体   中英

Receiving error when trying to use JSON.parse from internal storage data

My classmates and I are receiving the following error message when trying to use JSON.parse with data from internal storage. The code is given to us by our instructor so not sure what the issue is.

internal storage should hold nothing and initialize "pageViews" with 0 or if there is data in internal storage it should be an array.

Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse () at HTMLDocument.addPageView

HERE IS OUR CODE.

const pageViewsKeyName = "pageViews";

function addPageView() {

    let pageViews = localStorage.getItem(pageViewsKeyName);
    let arr = [];
    if (pageViews && pageViews.length > 0) {
        // get the array stored in local storage at pageViewsKeyName
        arr = JSON.parse(pageViews);

        // now we're able to insert an item in the page view data
        let newPageData = {
            "path": window.location.pathname,
            "timestamp": moment()
        };

        // now add new page data to the array
        arr.push(newPageData);

        // finally, we want to update our storage with the most up to date array
        localStorage.setItem(pageViewsKeyName, arr);
    }
}

JSON.parse is used to parse the string JSON value as JSON object. Looks like the pageViews already contains JSON object. Therefore you don't need to parse it. You can console.log(pageViews) to confirm that.

Yes, console.log(typeof PageViews) and check out what is it's data type. If it's an arry:

arr.push(PageViews[0]); // TODO for-loop to push all views into arr
If it's an object: 
arr.push(PageViews)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM