How to deal with two adjacent JSON objects?

Viewed 91

I have an API route that outputs records from a database as JSON. I would also like to output an HTTP status code.

I have tried echoing (as shown below) the HTTP status code & message before the return like above which functions how I would like, however, it is not valid JSON since I end up with two side by side JSON objects.

Here is a simplified view of my code:

private function json_books() {
  $query  = "SELECT title, description FROM books";
  $params= [];

  // creates and prints the HTTP status code message
  $msg = array("status" => "200", "message"=>"OK");
  echo json_encode($msg);

  //returns records from the database as JSON object
  return ($this->recordset->getJSONRecordSet($query, $params));
}

2 Answers

If you can get your recordset as an array, do it somehow like this:

private function json_books() {
  $query  = "SELECT title, description FROM books";
  $parameters = [];    // you are using the name "params" below!

  //returns records from the database as JSON object along the status message
  return json_encode(array(
    "status" => "200",
    "message" => "OK",
    "result" => $this->recordset->getRecordSet($query, $params)
  ));
}

You need to create a valid json structure. Something like this.

private function json_books() {
  $query  = "SELECT title, description FROM books";
  $parameters = [];

  // creates and prints the HTTP status code message
  $msg = array("status" => "200", "message"=>"OK");

  
  // This is prefered so you don't have to convert back and forth from json
  $records_array = $this->recordset->getArrayRecordSet($query, $params);
  
  // If you have to get the values as a json string then you need to convert them
  $records = $this->recordset->getJSONRecordSet($query, $params);
  $records_array = json_decode($records,true);
  
  $msg['data'] = $records_array;
  
  //returns records from the database as JSON string
  return json_encode($msg);
}
Related