Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string to a valid JSON object

hey there i saw many questions about this topic but none of them fit my question. i'm trying to use localStorage to store a user custom preferences, i try put an json object into a localStorage key and use it later on. the object at the beginning looks like that:

 Object {test: "{a:"b",c:"d"}"}

the JSON.parse method returns an error, what i done is that:

var local_storage = getAll();
$.parseJSON(JSON.stringify(local_storage.test.substring(0,0).substring(0,local_storage.length,-1)));

the output is :

{a:"b",c:"d"}

but i can't use it as local_storage.test.a why is that and what is the solution for that?

thx for the help :)

Edit!

Thanks to @Oli Soproni B, the solution is:

var key = {a:"b",c:"d"};
var l = JSON.stringify(key);
localStorage.setItem('test',l);
var local_storage = $.parseJSON(localStorage.getItem('test'));
console.log(local_storage);
console.log(local_storage.a);
like image 375
benjah Avatar asked Feb 17 '15 08:02

benjah


2 Answers

// data
    var k = {a:"b", c: "d"};
    // stringify json
    var l = JSON.stringify(k);
    // set item to local storage
    localStorage.setItem('test', l);

    // get item to local storage and parse data
    var local_storage = $.parseJSON(localStorage.getItem('test'));

    console.log(local_storage);

    Object {a: "b", c: "d"}

    console.log(local_storage.a);

    prints b

// or use 
 var local_storage = JSON.parse(localStorage.getItem('test'));
// in parsing the stringify json data
like image 162
Oli Soproni B. Avatar answered Oct 03 '22 00:10

Oli Soproni B.


Localstorage stores string, not object. So you need to convert object to string while storing and converting it to object while retrieving.

To store:

localStorage.setItem("key",JSON.stringify(obj));

To retrieve:

obj = JSON.parse(localStorage.getItem(obj));

See DEMO here.

like image 27
codingrose Avatar answered Oct 03 '22 01:10

codingrose