I need to create a json response to look like Stripe API response using PHP. This is the structure I want to get:
{ "body": "{n "error": "Please enter a valid secret key",n}n", }
This is the code I have so far:
first I create the array:
class Error { public $errors = array( 'body' => array( 'error' => false ), ); if ($this->errors['body']['error'] === false) { $this->errors['body']['error'] = 'Please enter a valid secret key' } $resp = json_encode( $this->errors ) echo wp_send_json( $resp ); }
but the result I get is: json_encode result:
{"body":{"error":"Please enter a valid secret key"}}
echo wp_send_json( $resp ) result:
res = "{"body":{"error":"Please enter a valid secret key"}}"
I don’t want the body to be encoded. What am I missing?
Advertisement
Answer
It looks like only the data is json_encode
d with the error…
$this->errors['body'] = json_encode( ['error' => 'Please enter a valid secret key']);
This won’t have the newlines in it, see if that is a problem.
Or to do this at the end (useful to include that you need this in the question)…
$resp = json_encode( $this->errors['body'], JSON_PRETTY_PRINT ); echo wp_send_json(['data' => $resp]);