Using stringify for nested JSON to use in localStorage

mojo1mojo2

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

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] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

LocalStorage 및 JSON.stringify JSON.parse

분류에서Dev

Use JSON.stringify and JSON.parse in resteasy

분류에서Dev

JQuery Mobile JSON Stringify

분류에서Dev

How to clone an array in javascript without using JSON.stringify or JSON.parse?

분류에서Dev

JSON.stringify 및 encodeuricomponent

분류에서Dev

JSON Stringify & AJAX parse errors

분류에서Dev

JSON Stringify & AJAX parse errors

분류에서Dev

Json stringify in JS and decoding in php

분류에서Dev

Parsing nested JSON using RetroFit for Android

분류에서Dev

Get the elements from nested JSON with Python using json lib

분류에서Dev

비동기 JSON.stringify

분류에서Dev

JSON.stringify an Array of HTML Elements/Strings

분류에서Dev

How do I safely JSON.stringify?

분류에서Dev

Fiddler HttpRequest Composer - json.stringify

분류에서Dev

Ajax JSON.stringify, POST variable is empty

분류에서Dev

Ajax JSON PHP Stringify not posting but returning successfully

분류에서Dev

오류 JSON stringify 형식

분류에서Dev

angularJS - POST array after JSON.stringify()

분류에서Dev

JSON.stringify 변경 날짜

분류에서Dev

Wakanda JSON.stringify 문제

분류에서Dev

JSON.stringify 및 $ http 요청

분류에서Dev

sessionStorage는 JSON.stringify 또는?

분류에서Dev

C# - How To Update Nested Values in JSON body using FormUrlEncodedContent?

분류에서Dev

Parsing nested JSON using body-parser and express

분류에서Dev

응답 JSON 객체 또는 JSON.stringify?

분류에서Dev

How to use different colors of Circles using JSON

분류에서Dev

PHP에서 JSON.stringify 디코딩

분류에서Dev

TypeError : JSON.stringify (...). then is not a function-React JS

분류에서Dev

JSON.stringify 대형 객체 최적화