jeremy
jeremy

Reputation: 433

How to display JSON object with an array using jQuery

I am using jQuery to parse and display data from a JSON file. I got everything to spit out in the browser but one of the keys in my JSON file has an array of values. So for example this is my JSON:

{
  "category" : "Stuff",
  "location_id" : {
    "longitude" : "-71.89237903999964",
    "latitude" : "41.6809076720005",
    "human_address" : "{\"address\":\"156 Plainfield Pike Rd\",\"city\":\"Plainfield\",\"state\":\"CT\",\"zip\":\"06374\"}"
  },
}

and here is my jQuery code:

$.getJSON('data.json', function(data) {
        var output = '<ul class="searchresults">';
        $.each(data, function(key, val) {
            if (val.item.search(myExp) != -1) {
                output += '<li>';
                output += '<p>' + "Category: " + val.category + '</p>';
                output += '<p>' + "Location: " + val.location_id + '</p>';
                output += '<p>' + "Business: " + val.business + '</p>';
                output += '</li>';
            }
        });
        output += '</ul>';
        $('#update').html(output);

I for some reason the output for the location_id comes up as [object, object]...can someone help me grab everything in that array?

Thanks a bunch!!!

Upvotes: 0

Views: 254

Answers (1)

Jordan Kasper
Jordan Kasper

Reputation: 13273

Your location_id value in the JSON is not an "Array", it's an "Object". And the default String value of an Object is [object Object]. Thus, you'll need to concat your string with the various pieces of that object, not the whole:

output += '<p>' + "Location: " + 
    val.location_id.longitude + ', ' + 
    val.location_id.latitude +
    '</p>';

Or you could take the entire location_id object and stringify the JSON. That won't be terribly human readable though:

output += '<p>' + "Location: " + JSON.stringify(val.location_id) + '</p>';

Upvotes: 2

Related Questions