asw1984
asw1984

Reputation: 763

Why is JSON.parse sometimes returning errors when used with a string array?

In the function below, I'm using JSON.parse() on some string arrays stored in window.sessionStorage so I can then use methods like .map().

window.sessionStorage = {
     myArray1: "["805746|search|4","980093062|search|0","980113648|search|1"]"
}

function mySessionStorage(strArr) {
    if (window.sessionStorage[strArr] &&
    typeof window.sessionStorage[strArr] === 'string' &&
    window.sessionStorage[strArr] !== '') {

      var myData = JSON.parse(window.sessionStorage[strArr]);

      if (myData && typeof myData === 'object') {
        // ....
      }
    }
}

...which is then called like so: mySessionStorage('myArray1')

But I'm seeing several errors logged in an analytics report and can't figure out why:

At first I thought the culprit was a trailing comma, or perhaps an issue with quotes. But since this doesn't appear to be happening 100% of the time, I've been unable to replicate the issue myself.

What am I missing?

Upvotes: 1

Views: 80

Answers (1)

FZs
FZs

Reputation: 18619

The problem is: in the declaration of myArray1 you used double quotes inside double quotes. So use apostrophes instead:

myArray1: '["805746|search|4","980093062|search|0","980113648|search|1"]'

Or escape quotes:

myArray1: "[\"805746|search|4\",\"980093062|search|0\",\"980113648|search|1\"]"

Upvotes: 1

Related Questions