Home  >  Q&A  >  body text

How to efficiently pass JSON data from PostgreSQL jsonb field to Javascript?

I'm looking for a smart solution to process some JSON data from a postgresql database using Javascript. I know I need to read the database via php and pass the data as an array to Javascript.

Usually 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 postgresql jsonb field in JSON format. So I'm hoping there's a way to pass the array more efficiently so that the PC doesn't have to repeat 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 doesn't work but should show roughly 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 great if someone could point me in the right direction.

P粉596161915P粉596161915426 days ago605

reply all(1)I'll reply

  • P粉744831602

    P粉7448316022023-09-13 10:07:37

    Okay, I'm feeling a little silly today. I found the solution, no need to create new array, just concatenate all the strings together.

    <?php
      require_once 'pgsql.php';
    
      $db = new database();
      $res = $db->select('drone001');
      while ($ds = pg_fetch_object($res)) {
        $jsondata .= $ds->data . ",";
      }
      $jsondata = "[" . rtrim($jsondata, ",") . "]";
    ?>
    
    <script type="text/javascript">
      var jsArray = JSON.parse('<?php echo $jsondata ?>');
      console.log(jsArray);
    </script>

    reply
    0
  • Cancelreply