2016-07-17 5 views
0

Ich verwende jQuery zum Parsen und Anzeigen von Daten aus einer JSON-Datei. Ich habe alles im Browser ausgespuckt, aber einer der Schlüssel in meiner JSON-Datei hat ein Array von Werten. So zum Beispiel, das ist meine JSON:Wie JSON-Objekt mit einem Array mit jQuery anzuzeigen

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

und hier ist mein 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); 

ich aus irgendeinem Grunde der Ausgang für die location_id kommt als [object, object] ... kann jemand mir helfen, alles in diesem Array zu greifen?

Danke ein Haufen !!!

Antwort

2

Ihr location_id Wert in der JSON ist kein "Array", es ist ein "Objekt". Und der Standard-String-Wert eines Objekts ist [object Object]. So müssen Sie die Zeichenfolge mit den verschiedenen Teilen dieses Objekts verketten, nicht dem ganzen:

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

Oder Sie könnten das gesamte location_id Objekt nehmen und die JSON stringify. Das wird jedoch nicht fürchterlich menschlich lesbar sein:

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