0

I'm using JSON to return an array of objects identical to each other in variable names, but differing in values. Rather than call the JSON function five times, is there a way that I can put objects within the JSON object so I can reference them like data.1.name, data.2.name, etc?

Current (terrible) code:

$(document).ready(function(){               
            var data = 'manliness=' + $("#manliness_level_number").html() + '&type=enemy';
            load_opponents();

            function load_opponents()
            {
                $.getJSON('http://arflux-rpg.com/game/index.php/handler/request', data, function(data){
                    if (data.success == true)
                    {
                        $("#enemy_list").append("<div id='" + data.name + "' class='enemy'><img class='enemy_image' src='http://dummyimage.com/100x100/000/fff&text=100x100' /><div class='enemy_manliness'>" + data.manliness + "</div><div class='enemy_richliness_reward'>"+data.richliness_reward+"</div><div class='enemy_manliness_reward'>"+data.manliness_reward+"</div></div>");
                    }
                    else
                    {
                        alert('Failed to load enemies and users! ' + data.err);
                    }
                });
            }
[code cut from here for brevity]
2
  • It sounds like you want to change the code that is generating this JSON. Can you show us the relevant PHP code? Commented Aug 14, 2011 at 16:50
  • FYI, what you are talking about isn't a JSON object but a JSON compatible object - pedantic yes but still important. Commented Aug 30, 2011 at 23:01

3 Answers 3

1

Put the objects in an array and then convert the array to JSON. Then you can access them as data[1].name and data[2].name etc.

Sign up to request clarification or add additional context in comments.

Comments

1

You probably want an array:

var data = [ { "name": "one"},
             { "name":"two"},
             { "name":"three"} ];

Then reference it like this:

data[i].name;

Comments

1

Just push the responding data into an array :)

var myArray = [];

$.getJSON('http://arflux-rpg.com/game/index.php/handler/request', data, function(data){
    if (data.success == true) {

        myArray.push(data);

    } else {
        alert('Failed to load enemies and users! ' + data.err);
    }
});

It's that easy :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.