简体   繁体   中英

How can I convert a json that contains array to javascript object?

I have json like below,

{
    "Message": "{\"Errors\":[\"The message.\",\"The message.\"],\"Infos\":[\"The message.\"],\"Warnings\":[\"The message.\"],\"Successes\":[\"The message.\"]}"
}

I would like to convert it to an object like below,

var obj = {
    Errors : new Array(),
    Infos : new Array(),
    Warnings : new Array(),
    Successes : new Array()
}

Note: I cannot make changes on the json.

I used jQuery.parseJson , but I couldn't do.

What you've posted is unusual: It's JSON defining an object with a single property, Message , which has a string value containing a second embedded JSON string. Very odd structure.

If you're really receiving that as JSON, then:

var outer = jQuery.parseJSON(theStringWithTheJSON);
var obj = jQuery.parseJSON(outer.Message);

Live Example | Source

But if you're retrieving that via ajax (for instance), jQuery may well have already done the first parseJSON for you, in which case you just need to do the second bit:

jQuery.ajax({
    /* ...other parameters here...*/
    success: function(data) {
        var obj = jQuery.parseJson(data.Message);
    }
});

Live Example | Source

But if you can, I would probably change the structure of the string you're receiving so it's not double-encoded like that:

{
    "Message": {
        "Errors": [
            "The message.",
            "The message."
        ],
        "Infos": [
            "The message."
        ],
        "Warnings": [
            "The message."
        ],
        "Successes": [
            "The message."
        ]
    }
}

Then you don't need to double-decode it, just the first decoding (which again may already be done for you, you haven't shown any code so it's hard to tell) is necessary and you can use var obj = yourVariable.Message; .

Live Example | Source

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM