0

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.

mojo1mojo2
  • 1,062
  • 1
  • 18
  • 28
  • I can't reproduce the problem: http://jsfiddle.net/fp8o2hr7/ – Quentin Dec 18 '14 at 07:00
  • I ran your code in chrome console, and it seems to be working fine. How are you getting the value? `localStorage.getItem("myData")` returns the correct result. – Pramod Karandikar Dec 18 '14 at 07:00
  • 1
    Have you tried console.log immediately before localStorage.setItem()? I've used JSON.stringify() fine local storage in the past... can you also show code retrieving value, and details of your browser and version... – Adam Dec 18 '14 at 07:00
  • I am using chrome, and I have used JSON.stringify before for nested objects and had it work fine, but this time it had issues. Especially with more complex objects. There might be an issue with how I was creating the object, but I have managed to fix the problem for the cases I'm encountering. – mojo1mojo2 Dec 19 '14 at 00:26
  • Could it be that you are using **arrays** with string keys instead of objects? That would be the expected result. – Felix Kling Dec 19 '14 at 00:28

1 Answers1

-1

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.

Community
  • 1
  • 1
mojo1mojo2
  • 1,062
  • 1
  • 18
  • 28
  • This is almost certainly the wrong approach. You should fix your data instead. – Felix Kling Dec 19 '14 at 00:29
  • 1
    My data is definitely an object of objects. I was able to convert the data into a string that resembles the form I wanted to have in localStorage (i.e. JSON). The approach is long-winded, but it worked. I just wanted to post my answer in case it helped someone else. – mojo1mojo2 Dec 19 '14 at 00:36
  • Bad answer. Stringify is exactly what you need for this. – wle8300.com Sep 03 '15 at 16:37