0

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?

1
  • 1
    Looks like you should run json_encode twice: first time for $this->errors['body'] and then for something like array('body' => $resp). For ex., sandbox.onlinephpfunctions.com/code/… Commented Jan 1, 2022 at 9:42

1 Answer 1

1

It looks like only the data is json_encoded 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]);
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, I need the encode to be at the end of the process. not when I place the error value.
@DavSev, updated - please make sure any requirements like having to encode at the end are clear in the question as it can easily be missed.
Thanks for the question edit and the clarification, I have done what you suggested. this is the code I have now: $errors_resp = json_encode( $this->errors['body'], JSON_PRETTY_PRINT ); $resp = [ 'body' => $errors_resp ]; echo wp_send_json( $resp ); but the echo result is res = {body: '"{\\"error\\":\\"Please enter a valid secret key\\"}"'} . I would expect the result to be : res = {body: "{\"error\":\"Please enter a valid secret key\"}"} I understand that the error object is encoded twice, how can I solve it? `
This is what I eventually did: ``` $resp['body'] = wp_json_encode( [ 'error' => [ 'message' => 'error message' ] ], JSON_PRETTY_PRINT ); wp_send_json( $resp );```

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.