• Hello,
    I have one request/idea to make WordPress even more amazing tool. ??
    I have an API where I would like to manipulate response formatting more specifically.

    I’ve figured out there is rest_pre_echo_response hook in class-wp-rest-server file that I might use, but there is no way to specify special options when the actual encoding of the response data is happening. Specifically, when json_encode is being used.

    My use-case for this is synced data handling from backend to front application.
    Say you send the following JSON to API during some bulk update on our custom REST API route:

    {
        "users": [
            {
                "name": "John",
                "age": 21
            },
            {
                "name": "Jane",
                "age": 16
            }
        ]
    }

    After running the validation checkups, there is an error with Jane’s age. When returning error response, I want to preserve array keys due to the organisational logic for our frontend. That means that I want to return them formatted such as:

    
    {
        "users": {
            "1": {
                "age": "The person must be at least 21 years old"
            }
        }
    }
    

    This case works perfectly because array with key “1” is preserved by default.
    The problem appears when both fields have errors, thus resulting in an array with keys “0” and “1”. If this is provided to the json_encode, it will return an array instead of an object with preserved keys.

    Following the first payload, lets say that both John’s and Jane’s ages are invalid, we would like to get this payload:

    
    {
        "users": {
            "0": {
                "age": "The person must be at least 21 years old"
            },
            "1": {
                "age": "The person must be at least 21 years old"
            }
        }
    }
    

    But with default encoding, we get this response:

    
    {
        "users": [
            {
                "age": "The person must be at least 21 years old"
            },
            {
                "age": "The person must be at least 21 years old"
            }
        ]
    }
    

    Please notice that in the second response we get an array instead of the desired object.

    I understand that this is the default behaviour of json_encode without provided options. For now, we covered this case in our frontend application so it is not a blocker, but a new feature proposal. ??

    To achieve forementioned key preservation, I need to provide JSON_FORCE_OBJECT option when calling json_encode. The problem is that I can’t hook into the wp_json_encode behaviour to extend with provided options.

    I would like to suggest a filter hook inside of the wp_json_encode which will filter $options before passing these to the json_encode.

    Just to give you an idea, this is a code example of how the solution might look like:

    
    function wp_json_encode( $data, $options = 0, $depth = 512 ) {
            //Here I added new filter usage which will add the provided option on next wp_json_encode call
            $options = apply_filters('wp_json_encode_options', $options);
    
    	$json = json_encode( $data, $options, $depth );
    
    	// If json_encode() was successful, no need to do more sanity checking.
    	if ( false !== $json ) {
    		return $json;
    	}
    
    	try {
    		$data = _wp_json_sanity_check( $data, $depth );
    	} catch ( Exception $e ) {
    		return false;
    	}
    
    	return json_encode( $data, $options, $depth );
    }

    With this approach it will be possible to hook into and achieve previously described behaviour without messing up other behaviours (of course, unless someone directly uses it in an inappropriate way).

    Please share your thoughts and let me know if this is something that makes sense to You and if this is something that might be changed in the near future. I can also create a Pull Request/Merge request if necessary, just point me in the right direction for this.

    • This topic was modified 3 years, 7 months ago by bkrnetic.
    • This topic was modified 3 years, 7 months ago by bkrnetic.
    • This topic was modified 3 years, 7 months ago by bkrnetic.
    • This topic was modified 3 years, 7 months ago by bkrnetic.
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
  • The topic ‘Expansion of wp_json_encode method with hooks’ is closed to new replies.