Graeme1995's avatar

How to select "message" from this json response

Currently I am having to use an API (from an external source) to do a post request to themselves. This is all fine and working however I want to be able to log any errors (using the info() function) it may return to keep on record. The trouble I am having is retrieving the "message" from their JSON response. This is the JSON response I am getting when dumping:

{#1266 ▼
  +"content": """
    {\r\n
      "message": "An error has occurred."\r\n
    }
    """
  +"status": 500
  +"contentType": "application/json; charset=utf-8"
}

I am able to display the status on its own using $status = json_decode($response->status); however this is not the case with "message".

I have tried $message = json_decode($response->content->message); however I get "Trying to get property 'message' of non-object"

I also tried $message = json_decode($response['content']['message']); but I get "Cannot use object of type stdClass as array".

I am running out of ideas on how I can retrieve just the "message" to display in the log. Below is a snippet of how I am trying to log:

        if($response->status != 200){

            $status = json_decode($response->status);
            $message = json_decode($response['content']['message']);

            info(auth()->user()->log_reference . " encountered an error. Error ({$status}) - {$message}");
            return redirect()->back()->with('error', 'An error occured processing your details.');

        }

If I dump out json_decode($response->content) I am left with the following:

{#1267 ▼
  +"message": "An error has occurred."
}

Does the "+" before "message" mean anything?

0 likes
3 replies
realrandyallen's avatar

Try:

$status = json_decode($response);

$message = $status->content->message;
realrandyallen's avatar
Level 44

@GRAEME1995 - Sorry, it looks like the response is already json, you should be able to just do:

$message = $response->content->message
1 like

Please or to participate in this conversation.