OK_Sooner OK_Sooner - 4 months ago 7
JSON Question

Calling JSON properties from an array

I am trying to call a single JSON key in JavaScript but I keep getting an 'undefined' value returned

I used PHP to extract the information from a MySQL database, and using

json_encode ($array, JSON_FORCE_OBJECT)
, created an array of JSON objects in PHP.

PHP code:

require 'credentials.php';

$result = "Select * From table1";

$query = mysqli_query($conn, $result);

$json_array = array();

while($row = mysqli_fetch_assoc($query)){
$jsondata=json_encode($row, JSON_FORCE_OBJECT);
array_push($json_array, $jsondata);

};


Then I passed the array of JSON objects to a JavaScript tag:

var data = <?php print_r(json_encode($json_array, JSON_FORCE_OBJECT));?>;
console.log(data[0].keyToGetValueOf);


Suggestion as to how to retrieve the key for only 1 of the objects in the array?

Answer

This is how you'd get the keys natively

console.log(Object.keys(data[0]));

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Comments