syntaxerror json.parse unexpected character at line 1 column 1 of the json data
Asked Answered
Y

1

6

i Don't know what is the problem i got above syntax error in json.parse I m using like below code

Storage.prototype.setObject = function(key, value) {
   this.setItem(key, JSON.stringify(value));
}

Storage.prototype.getObject = function(key) {
   var value = this.getItem(key);
   return value && JSON.parse(value);
}

function main() {
   var data = { 
       "a":"something1",
       "b":"something2"
   };
   sessionStorage.setObject('data',data);
   var newData = sessionStorage.getObject('data');
   console.log(newData);  
}

while calling getObject('data') i got the error in " firefox " while " no error " in chrome pls help me to figure out the problem i run above sample code separately and it works fine for me but in my project where i m doing something same it cause error.

Yuji answered 23/5, 2014 at 18:6 Comment(3)
I bet this.getItem(key) is not returning what you expect, just debug it.Dionysian
i run above sample code separately and it works fine for me but in my project where i m doing something same it cause error. Try to isolate your problem in your project. Because it looks like it is a specific data that you are dealing with in your project that is causing the problem to happen.Gomuti
Debug: what is console.log(value);? Put it before you try to parse and return.Attain
U
1

I don't get any errors in either Firefox or Chrome. However, you can catch this exception for debugging by adding a try/catch block to the getObject method

Storage.prototype.getObject = function(key) {
    var value = this.getItem(key);
    if (value) {
        try {
            value = JSON.parse(value);
        } catch (err) {
            console.error("Error parsing stored data: " + err);
        }
    }
}
Understandable answered 17/9, 2014 at 15:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.