简体   繁体   中英

How to parse (and access) array of object

I would like to parse and print a JSON composed by an array of objects passed to JavaScript from PHP through GET request, I tried the "standard way" but my code doesn't work (but works with simple JSON)

PHP:

ob_start();
for ($i=0; $i<count($id); $i++){
    $array[]=new Field($id[$i], $en[$i], $it[$i]);
}
print_r($array); // IT WORKS PROPERLY

ob_end_clean();
header('Content-Type: application/json');
echo json_encode($array);

JavaScript:

$.get("../GetFieldsForLanguage.php", function(data, status){
var str = JSON.stringify(data);
console.log(str);
var form = JSON.parse(str);
var count = Object.keys(data).length;
for (var i=0; i<count; i++)
{
   $('#it').append(
      $('<tr />').append(
         $('<th />', {text: form[i].**WHAT**}),
         $('<th />').append(
            $('<input />', { name: form[i]., placeholder: form[i]. type: 'text' })
         )
      )
   )
}

And that's an example of how JSON is printed by echo:

[
 {"ev":"Description","iv":"...","id":"1"},
 {"ev":"Surface","iv":"...","id":"2"},
 {"ev":"Locals","iv":"...","id":"3"}
]

I think $.getJSON is what you're after, example.

$.getJSON( "../GetFieldsForLanguage.php", function( data ) {
    var items = [];
    var count = data.length;
    $.each( data, function( key, val ) {
        items.push( "<li id='" + key + "'>" + val + "</li>" );
    });
    $( "<ul/>", {
       "class": "my-new-list",
       html: items.join( "" )
    }).appendTo( "body" );
});

Hope this helps!

Few observations :

  • Why JSON.stringify(data) and JSON.parse(str) as data is already a JSON Object ?. There is no mean to stringify and parse again.
  • Your response data is an array of objects as per the JSON you posted in OP. So, why Object.keys(data) ?
  • Instead of var count = Object.keys(data).length it should be var count = data.length as data is an array not an JS object .

Working Fiddle

 var data = [{"ev":"Description","iv":"...","id":"1"},{"ev":"Surface","iv":"...","id":"2"},{"ev":"Locals","iv":"...","id":"3"}]; var count = data.length; for (var i=0; i<count; i++) { $('#it').append( $('<tr />').append( $('<th />', {text: data[i].ev}), $('<th />').append( $('<input />', { name: data[i].ev, placeholder: data[i].iv, type: 'text' }) ) ) ) } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="it"> </div> 

If your data is always an array :

 var data = [ {"ev":"Description","iv":"...","id":"1"}, {"ev":"Surface" ,"iv":"...","id":"2"}, {"ev":"Locals" ,"iv":"...","id":"3"} ]; console.log(data); data.forEach(function (value) { $('#it').append( $('<tr />').append( $('<th />', {text: value.ev}), $('<th />').append( $('<input />', { name: value.id, placeholder: value.iv }) ) ) ) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="it"></div> 

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