I am looking for a smart solution to process some JSON data from a postgresql database in Javascript. I understand that I need to read the database via php and pass the data as an array to Javascript.
Normaly you would do something like this:
<?php
$phpArray = array('apple', 'banana', 'orange');
$jsonString = json_encode($phpArray);
?>
<script>
var jsonString = '<?php echo $jsonString ?>';
var jsArray = JSON.parse(jsonString);
</script>
But my data is already stored in JSON format in a postgresql jsonb field. So I hope there is a way to pass the array more effectively so the PC doesn't have to iterate the same data twice.
root@monitor:~ $ sudo -u postgres psql
postgres=# \c monitor
monitor=# SELECT * FROM "drone001";
id | data
---+-----------------------------------------------------------------------------------------------
1 | {"RX": 13.7, "Speed": 10.1, "Azimuth": 897, "Heading": 125, "DateTime": "2023-03-19 04:14:49"}
2 | {"RX": 13.4, "Speed": 10.2, "Azimuth": 896, "Heading": 125, "DateTime": "2023-03-19 04:14:47"}
3 | {"RX": 13.3, "Speed": 10.1, "Azimuth": 896, "Heading": 125, "DateTime": "2023-03-19 04:14:45"}
4 | {"RX": 13.7, "Speed": 10.1, "Azimuth": 896, "Heading": 127, "DateTime": "2023-03-19 04:14:43"}
5 | {"RX": 13.1, "Speed": 10.1, "Azimuth": 896, "Heading": 125, "DateTime": "2023-03-19 04:14:41"}
[...]
this code does not work, but should show approximately what I have in mind.
<?php
require_once 'pgsql.php';
$db = new database();
$res = $db->select('drone001');
$jsondata = array();
while ($ds = pg_fetch_object($res)) {
$jsondata[] = $ds->data;
}
?>
<script type="text/javascript">
var jsArray = JSON.parse('<?php echo $jsondata ?>');
console.log(jsArray);
</script>
It would be nice if someone could point me in the right direction.