JSON to Array react, jquery

17,697

Assuming your JSON is like this as posted:

{"response": {"user": [{"username": "", "description": "", "picture_url": "", "name": "", "phone": ""}]}, "success": true}

You already have the exact data structure you want at .response.user.

So code would be simple:

var json = '{"response": {"user": [{"username": "", "description": "", "picture_url": "", "name": "", "phone": ""}]}, "success": true}';
var obj = JSON.parse(json);
var theArrayYouWant = obj.response.user;

This doesn't require any transformation at all (other than deserializing the JSON string), you are just extracting a portion of the data structure represented in JSON.

Share:
17,697
Admin
Author by

Admin

Updated on June 16, 2022

Comments

  • Admin
    Admin almost 2 years

    I have json data obtained form my server and i want to put in a list, i already read Convert JSON To Array Javascript and Converting data from JSON to JavaScript array but i can't figure out what of all the options can i use in my code my json is like this:

    {"response": {"user": [{"username": "", "description": "", "picture_url": "", "name": "", "phone": ""}]}, "success": true}

    and i want to put it on an array like this:

    [{username: "",description: "", picture_url: "", name: "", phone: ""}]

    what can i do for this? i already try the answers of this: Converting JSON Object into Javascript array

    i also try some functions like this:

    $.each(data, function(i,obj){
                    $(arr).append(obj.username+'</br>');
                    $(arr).append(obj.description+'</br>');
                    $(arr).append(obj.name+'</br>');
                });
    

    and this:

    var results = data;
                var arr = [], item;
                for (var i = 0, len = results.length; i < len; i++) {
                    item = results[i];
                    arr.push({username: item.username, description: item.description, name: item.name});
                }
    

    but with the second one dont show anything and dont show any error, with the first one, showme an unespecthed error arr is not defined.

  • Admin
    Admin over 8 years
    i cant modify the server side script