I am storing a json
first in localstorage
and then again storing it in final json
but I am getting extra backslash
in my final json
. My code is:
<!DOCTYPE html>
<html>
<body>
<script>
var mi = [{
"name": "Alex",
"address": "abc"
},
{
"name": "George",
"address": "efg"
}
]
localStorage.setItem("myData", JSON.stringify(mi))
var FinalJson = {
"Collected values" : localStorage.getItem("myData"),
"Place" : "washington"
};
document.write(JSON.stringify(FinalJson));
</script>
</body>
</html>
Output I am getting is:
{"Collected values":"[{\"name\":\"Alex\",\"address\":\"abc\"} {\"name\":\"George\",\"address\":\"efg\"}]","Place":"washington"}
Where am i going wrong that I am getting this extra backslash
. How can I remove the extra backslashes
? P.S. I don't want to directly store the variable mi
in my FinalJson
, as it contains some more plicated values which I have removed here for simplicity.
I am storing a json
first in localstorage
and then again storing it in final json
but I am getting extra backslash
in my final json
. My code is:
<!DOCTYPE html>
<html>
<body>
<script>
var mi = [{
"name": "Alex",
"address": "abc"
},
{
"name": "George",
"address": "efg"
}
]
localStorage.setItem("myData", JSON.stringify(mi))
var FinalJson = {
"Collected values" : localStorage.getItem("myData"),
"Place" : "washington"
};
document.write(JSON.stringify(FinalJson));
</script>
</body>
</html>
Output I am getting is:
{"Collected values":"[{\"name\":\"Alex\",\"address\":\"abc\"} {\"name\":\"George\",\"address\":\"efg\"}]","Place":"washington"}
Where am i going wrong that I am getting this extra backslash
. How can I remove the extra backslashes
? P.S. I don't want to directly store the variable mi
in my FinalJson
, as it contains some more plicated values which I have removed here for simplicity.
- It's just escaping the string, try parsing the data back and see if it resolves it self, as you're probably not planning on just throwing the JSON out on the page as a string ? – adeneo Commented Jan 12, 2014 at 21:01
-
1
Oh, it's double stringified, do
"Collected values" : JSON.parse(localStorage.getItem("myData"))
– adeneo Commented Jan 12, 2014 at 21:02
2 Answers
Reset to default 4It's stringified twice
var FinalJson = {
"Collected values" : JSON.parse(localStorage.getItem("myData")),
"Place" : "washington"
};
http://jsfiddle/Kh5Br/
var mi = [{
"name": "Alex",
"address": "abc"
},
{
"name": "George",
"address": "efg"
}
];
localStorage.setItem("myData", JSON.stringify(mi))
var tes = JSON.parse(localStorage.getItem("myData")); //It was "work". I thougt you missed that
var FinalJson = {
"Collected values" : tes,
"Place" : "washington"
};
document.write(JSON.stringify(FinalJson));
document.write(tes);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745422336a4627020.html
评论列表(0条)