I have a nested JSON object given by
var data = {
"animal":
{
"canine": "dog",
"feline": "cat"
},
"bug": "beetle",
"carrot":
{
"color": "orange",
"type": "vegetable"
},
"population": 100
};
I have been trying to use JSON.stringify to store this information by
localStorage.setItem("myData", JSON.stringify(data));
but it does not store the nested parts of the JSON object. For example, it ignores it and instead shows
"animal":{}
How might I simply be able to resolve this issue? I have seen solutions involving modifying ajax to become synchronous, but I didn't really understand what was happening.
I just want it so that I can obtain in console
console.log(JSON.stringify(data))
//{"animal":{"canine":"dog","feline":"cat"},"bug":"beetle","carrot":{"color":"orange","type":"vegetable"},"population":100}
so if there is a method that does not use stringify, that will be great too.
I created a solution that worked for me.
I wrote a recursive function that uses a preorder algorithm through the object. It is not complete, obvious improvements could be made to make it more generic (especially with arrays of objects, or things like that), but it works on a basic level quite well I find.
function recursiveObjStr(obj, str)
{
str += "{";
for(var inst in obj)
{
str += "\"" + inst + "\"" + ":";
if(isArray(obj[inst]))
{
str += "[";
for(var inst2 in obj[inst])
{
str += "\"" + obj[inst][inst2] + "\"" + ",";
}
str = str.substring(0,str.length-1);
str += "]";
}
else if(typeof(obj[inst]) == "object")
{
str = recursiveObjStr(obj[inst], str);
}
else if(typeof(obj[inst]) == "function")
{
str += obj[inst];
}
else
{
if(!(isNaN(obj[inst])))
{
str += obj[inst];
}
else if(typeof(obj[inst]) == "boolean")
{
str += obj[inst];
}
else
{
str += "\"" + obj[inst] + "\"";
}
}
if(str[str.length-1] !== ",")
{
str += ",";
}
}
str = str.substring(0, str.length - 1);
str += "},";
return str;
}
Using this isArray() function taken from https://stackoverflow.com/a/218833/4309934
function isArray ( obj ) {
return isObject(obj) && (obj instanceof Array);
}
There is an issue with having an additional comma at the end, so to remove it I use substring again. For example, with data defined as in the original question, it can be used by
var str = "";
str = recursiveObjStr(data, str);
//console.log(str) gives {"animal":{"canine":"dog","feline":"cat"},"bug":"beetle","carrot":{"color":"orange","type":"vegetable"},"population":100},
str = str.substring(0, str.length-1);
//removes the comma
Feel free to find improvements to this method.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다