Make WordPress Core

Opened 6 weeks ago

Closed 4 weeks ago

Last modified 6 days ago

#66267 closed defect (bug) (fixed)

Abilities API: Preserve empty object values when serializing schemas and results to JSON

Reported by: gziolo Owned by: gziolo
Priority: normal Milestone: 7.2
Component: Abilities API Version: 6.9
Severity: normal Keywords: has-patch has-unit-tests needs-dev-note
Cc: Focuses:

Description (last modified by gziolo)

When an ability uses an empty PHP array to represent an object, JSON encoding produces [] instead of {}. This can affect both defaults in published schemas and ability results sent to clients.

WP_Ability::execute() accepts PHP arrays for output schemas with type: object. Without schema-aware preparation, an empty result passes validation but is serialized as a JSON array:

  • The REST run endpoint returns it through rest_ensure_response().
  • The AI client wraps it in a FunctionResponse, whose result is later encoded for the model.

The resulting JSON does not match the output schema, and strict clients may reject it.

For example, core/settings-get (#64605) returns an empty map when no setting matches. Clients receive [], although the output schema describes an object.

Core already handles empty object defaults through wp_prepare_json_schema_for_client(). In [64315], this was extended to union types that include object but exclude array, such as array( 'object', 'null' ). This ticket covers consistent handling of empty objects across schemas and results exposed through the Abilities API.

Expected behavior

  • Convert empty PHP arrays to {} when the schema allows objects but not arrays.
  • Preserve [] when both object and array are allowed.
  • Apply preparation recursively to properties, patternProperties, additionalProperties, and array items.
  • Account for applicable anyOf and oneOf branches, including nested values described within them.
  • Support arrays, stdClass, and JsonSerializable values.

Proposal

Add a helper alongside wp_prepare_json_schema_for_client(), such as wp_prepare_json_value_for_client( $value, $schema ), to prepare execution results for JSON clients.

Use it after output validation:

  • in the REST run controller, before rest_ensure_response();
  • in the AI client function resolver, before creating the FunctionResponse.

WP_Ability::execute() remains unchanged, so direct PHP callers receive the original ability result. Preparation preserves the intended JSON representation of existing values.

Change History (45)

#1 @gziolo
6 weeks ago

  • Owner set to gziolo

#2 @sukhendu2002
6 weeks ago

I reproduced this on current trunk. An ability returning array() with an output schema of type: object passes WP_Ability::execute() validation, but the REST response encodes as [], and the AI client produces "response":[].

The proposed placement looks correct. For mixed types, I suggest converting an empty PHP array when object is allowed and array is not. Therefore, object|null should become {}, because the value cannot represent null. For object|array, it should remain [], because both JSON shapes satisfy the schema and the PHP value is ambiguous. This also avoids making the result depend on the order of types in the schema.

If this direction looks final, I’m happy to work on the PR and add the related test coverage.

One related clarification: PR #14068 covers encoding empty object schema defaults through wp_prepare_json_schema_for_client(). It does not prepare runtime ability output values, so this ticket is still needed.

#3 @gziolo
6 weeks ago

@sukhendu2002, sounds like a solid plan. Good point about covering the case where both an array and object are listed as allowed types. We should only cast when it’s clear that an empty array represents an object 👍

Feel free to open PR and I will help to take it to the finish line.

This ticket was mentioned in ​PR #14068 on ​WordPress/wordpress-develop by ​@gziolo.


6 weeks ago
#4

  • Keywords has-patch has-unit-tests added

What?

Adds a test for how wp_prepare_json_schema_for_client() handles the default of a schema. It uses a data provider with three cases:

  • An empty default on an object schema is encoded as {}.
  • A non-empty default on an object schema stays the same.
  • An empty default on an array schema stays [].

Why?

In PHP, an empty array is encoded as [] in JSON. For an object schema, clients expect {}. The helper already fixes this, but only a nested property was tested before, not the root schema.

Abilities rely on this. They can use 'default' => array() in an object input schema, and both the REST API and the AI client still send {}. This came up in ​https://github.com/WordPress/wordpress-develop/pull/12141.

Testing

npm run test:php -- --filter test_wp_prepare_json_schema_for_client_encodes_default

Trac ticket: https://core.trac.wordpress.org/ticket/66267

Use of AI Tools

The test and this description were drafted with Claude Code and reviewed by me.

🤖 Generated with ​Claude Code

This ticket was mentioned in ​PR #14139 on ​WordPress/wordpress-develop by ​@sukhendu2002.


6 weeks ago
#5

What

Adds wp_prepare_json_value_for_client() to prepare ability results according to their output schema before sending them to JSON clients.

The helper:

  • Converts an empty PHP array to an object when the schema allows object but not array.
  • Leaves the value as [] when both object and array are allowed.
  • Recursively prepares properties, patternProperties, additionalProperties, and array items.
  • Supports arrays, stdClass, and JsonSerializable values.

Why

An ability can return an empty PHP array for an output schema with type: object. Server-side validation accepts that value, but JSON encoding produces [] instead of {}.

This violates the published output schema and can be rejected by strict clients or AI providers expecting an object. When both object and array are allowed, the empty array remains [] because its intended JSON type is ambiguous.

Testing

npm run test:php -- --filter 'Tests_JSON_Schema|Tests_REST_API_WpRestAbilitiesV1RunController|Tests_AI_Client_AbilityFunctionResolver|Tests_AI_Client_PromptBuilder'

Use of AI Tools

AI assistance: Yes
Tool(s): Pi agent
Model(s): GPT-5.6 Sol
Used for: Initial code skeleton, Test drafting

#6 @gziolo
5 weeks ago

@sukhendu2002, I updated ​https://github.com/WordPress/wordpress-develop/pull/14068 based on your feedback. Good catch with properties supporting multiple types.

#7 @gziolo
5 weeks ago

In 64315:

JSON schema: Send empty object defaults as {} for union types

wp_prepare_json_schema_for_client() already changes an empty array default to an object when the type is object. Now it also does this when the type is a list that includes object but not array, like array( 'object', 'null' ). If array is allowed, the default stays [].

Developed in ​https://github.com/WordPress/wordpress-develop/pull/14068.
Follow-up to [62591].

Props sukhendu2002.
See #66267.

#9 @gziolo
5 weeks ago

  • Description modified (diff)
  • Summary Abilities API: Send empty object results as {} to JSON clients → Abilities API: Preserve empty object values when serializing schemas and results to JSON

This ticket was mentioned in ​PR #14233 on ​WordPress/wordpress-develop by ​@gziolo.


5 weeks ago
#10

WP_Ability::normalize_input() currently applies only a top-level input default. Defaults on missing properties inside supplied objects or array items never reach validation or the ability callback.

Apply declared property defaults recursively through properties, patternProperties, additionalProperties, and array items. For example, input array( 'options' => array() ) becomes array( 'options' => array( 'count' => 42 ) ) when options.count declares default: 42. Normalization happens before the existing input filter, validation, permission checks, and execution.

Existing property values, including null, false, 0, and empty values, are preserved. Missing containers are created only when they have an explicit default, and array items are never invented. Top-level null retains its existing default-selection behavior. Nested stdClass inputs and object defaults are cloned to avoid mutating caller-owned values or the schema.

Related Trac ticket: https://core.trac.wordpress.org/ticket/66267

This is a separate input-normalization proposal arising from that review; it adds declared defaults to input rather than correcting the JSON representation of output values. Defaults within anyOf/oneOf branches are not resolved by this implementation.

Testing

  • 40 data-provider cases cover nested containers, explicit values, nullable types, array keys, and property defaults.
  • Additional tests cover object immutability and defaults reaching the input filter, validation, permissions, and execution.
  • Abilities API, REST abilities, and AI client resolver/prompt-builder tests: 655 tests, 1,735 assertions passed.
  • PHPCS passed for both changed files; git diff --check passed.

Use of AI Tools

AI assistance: Yes
Tool(s): OpenAI Codex
Used for: Implementation, test creation, local test execution, and pull request description.

​@gziolo commented on ​PR #14233:


5 weeks ago
#11

I did some more analysis on this change, and here is what I found.

The main idea still holds. Today a nested default is only documentation, so the callback has to repeat the value by hand ($input['count'] ?? 42), and nothing checks that the two match. Applying it in core makes the schema the single source of truth. That works well for reads and creates, where "not provided" means "use the default".

Updates are trickier. There, "not provided" usually means "keep the current value", so a default would overwrite something the caller never sent. REST avoids this on purpose: it copies defaults only for CREATABLE endpoints, not EDITABLE.

This matters for existing abilities. Since 6.9, authors wrote schemas knowing nested defaults are ignored, and some may reuse the same schema for reading and updating (the settings schema from show_in_rest['schema'] is one example). After this change, an "update post" ability with status defaulting to draft would unpublish a post when the caller sends only a new title. There would be no error, just changed data. Because of that, I'm leaning toward making nested defaults opt-in per ability. The other option is to first search the plugin directory for this pattern and then clearly document "don't declare defaults on update fields".

On validation, applying defaults before validate_input() is the right order. I found two things to address:

  • Defaults now get validated, so a bad one (like "10" on an integer) starts failing calls that passed before. A _doing_it_wrong() at registration could catch this early.
  • REST coercion runs too early. coerce_input_to_schema() checks the raw input, before defaults are added. If a property is required with a default, that check fails and the whole input skips coercion. Later the default fills it in and validation passes, but the callback gets strings like "5" instead of 5 from GET requests. Running coercion after normalize_input() would fix it.

I'm still thinking this through. Given the possible impact on existing abilities, I'm not sure this change should move forward right now. Any feedback is very welcome.

#12 @gziolo
4 weeks ago

In 64592:

Abilities API: Preserve empty objects in JSON results

Empty PHP arrays representing objects are incorrectly encoded as []
instead of {}. Add wp_prepare_json_value_for_client() to prepare ability
results according to their output schemas before JSON encoding.

Apply it to AI client results and associative REST results, preserving
compatibility with _fields and _embed processing.

Props sukhendu2002, gziolo.
See #66267.

This ticket was mentioned in ​PR #14542 on ​WordPress/wordpress-develop by ​@gziolo.


4 weeks ago
#15

Schema defaults containing empty objects can be exposed as JSON arrays. For example, an object default with an object-valued settings property currently encodes as {"settings":[]} instead of {"settings":{}}. Defaults whose object type is determined by matching anyOf or oneOf branches are also missed by the existing direct type check.

Prepare each existing default through wp_prepare_json_value_for_client() so defaults receive the same nested-value and branch handling as other JSON values. Array defaults remain arrays when a matching schema allows them. This shares the helper's existing scope; it does not add full draft-04 evaluation or reference resolution.

Regression tests reuse the value-preparation data provider and cover nested defaults with properties, array items, pattern properties, and additional properties. PHPDoc describes the purpose and behavior, and schema/value functions are grouped with their respective helpers.

Testing

  • npm run test:php -- --group json-schema — passed (78 tests, 135 assertions).
  • php vendor/bin/phpcs src/wp-includes/json-schema.php tests/phpunit/tests/json-schema.php --report=summary — passed.
  • git diff --check — passed before committing.

Use of AI Tools

AI assistance: Yes
Tool: OpenAI Codex
Used for: Investigating the issue, implementing the fix and regression tests, revising PHPDoc and function order, running checks, and drafting this PR description under contributor direction.

#17 @gziolo
4 weeks ago

  • Resolution → fixed
  • Status assigned → closed

In 64594:

JSON Schema: Prepare default values according to their schemas

Use wp_prepare_json_value_for_client() to normalize existing schema defaults, preserving empty objects within nested values and resolving matching anyOf and oneOf branches. Defaults remain arrays when a matching schema allows arrays.

Add regression coverage for nested defaults and clarify the schema and value preparation PHPDoc.

Follow-up to [64592], [64315].
Developed in ​https://github.com/WordPress/wordpress-develop/pull/14542.

Fix #66267.

This ticket was mentioned in ​PR #14547 on ​WordPress/wordpress-develop by ​@jorgefilipecosta.


4 weeks ago
#19

Follow up to ​https://github.com/WordPress/wordpress-develop/pull/14139 (r64592).

What

  • The run endpoint now prepares root empty arrays and numeric collections against the output schema, so an empty object result encodes as {} instead of [].
  • With _fields or _embed the old behavior stays: the REST server's processing for those expects arrays at the root and in collection items, and fatals on stdClass (https://core.trac.wordpress.org/ticket/66230).
  • core/settings-get with no matching settings (e.g. { group: 'nonexistent' }) currently returns []. The JS client (executeAbility()) then rejects it with ability_invalid_output, because the output schema is an object.
await wp.apiFetch( { path: wp.url.addQueryArgs( '/wp-abilities/v1/abilities/core/settings-get/run', { input: { group: 'nonexistent' } } ) } );
// Before: []
// After:  {}

Issue found while testing the query abilities through the JS client; the fix was drafted with AI assistance and reviewed by me.

Testing

Verify unit tests are passing:

npm run test:php -- --filter test_output_is_prepared_for_json_clients

​@gziolo commented on ​PR #14547:


4 weeks ago
#20

I noted in ​https://github.com/WordPress/wordpress-develop/pull/14139 that we should follow-up and figure out how to map [] to {} in a way that doesn't break REST API handler when global handlers like _fields or _links get passed. Casting to (object) in the ability doesn't resolve the problem.

This ticket was mentioned in ​PR #14552 on ​WordPress/wordpress-develop by ​@jorgefilipecosta.


4 weeks ago
#21

Follow up to https://core.trac.wordpress.org/changeset/64503 and https://core.trac.wordpress.org/changeset/64592.

This PR removes the private _rest_cast_empty_objects_from_schema() helper and uses the public wp_prepare_json_value_for_client() instead, so there is a single function that prepares empty objects according to a schema:

  • The view config and entity fields endpoints call wp_prepare_json_value_for_client().
  • WP_REST_View_Config_Controller::cast_empty_objects() (since 7.1) is kept and delegates to it.
  • The private helper was added in this release cycle, so it is removed without deprecation.

wp_prepare_json_value_for_client() also handles cases the private helper missed: it recurses into the matching oneOf/anyOf branch (e.g. a form field children: [ [] ] is now [ {} ]), patternProperties, stdClass and JsonSerializable values, and keeps [] when the schema also allows an array. No view config or entity fields schema allows both an object and an array, so the existing responses are unchanged.

The change was drafted with AI assistance and reviewed by me.

Testing

Verify unit tests are passing:

npm run test:php -- --group entity-fields,view-config,json-schema

#22 @jorgefilipecosta
4 weeks ago

In 64602:

REST API: Use wp_prepare_json_value_for_client() for view configs and entity fields.

Removes the private _rest_cast_empty_objects_from_schema() helper, so a single function prepares empty objects according to a schema. The view config and entity fields endpoints now call wp_prepare_json_value_for_client(), and WP_REST_View_Config_Controller::cast_empty_objects() delegates to it. The private helper was added in this release cycle, so it is removed without deprecation.
wp_prepare_json_value_for_client() also recurses into the matching oneOf/anyOf branch and into patternProperties, and keeps [] when the schema also allows an array. No view config or entity fields schema allows both an object and an array, so the existing responses are unchanged.

Developed in ​https://github.com/WordPress/wordpress-develop/pull/14552.

Follow-up to [64503], [64592].

Props jorgefilipecosta, oandregal.
See #66267.

#24 @davidbaumwald
4 weeks ago

In 64604:

REST API: Cleanup empty test file.

[64602] was meant to delete this file.

Follow-up to [64602].

Props audrasjb, SergeyBiryukov.
See #66267.

​@jorgefilipecosta commented on ​PR #14547:


4 weeks ago
#25

I noted in #14139 that we should follow-up and figure out how to map [] to {} in a way that doesn't break REST API handler when global handlers like _fields or _links get passed. Casting to (object) in the ability doesn't resolve the problem.

Hi @gziolo this PR was updated and addressed these issues.

​@gziolo commented on ​PR #14547:


4 weeks ago
#26

Could we let controllers explicitly opt out of _fields filtering, _embed processing, and response link injection?

The problem extends beyond objects to scalar values, where these transformations have no meaningful application. Currently, _fields can trigger a type error, embedding silently does nothing, and link injection can fail or change the response’s type. Broadening array-specific helpers to accept arbitrary values doesn’t establish consistent support for these features.

The ability execution controller could disable all three explicitly, preserving the ability’s output schema and making behavior predictable regardless of whether the result is an object, array, or scalar.

This ticket was mentioned in ​PR #14671 on ​WordPress/wordpress-develop by ​@jorgefilipecosta.


4 weeks ago
#27

Follow up to ​https://github.com/WordPress/wordpress-develop/pull/14547#issuecomment-6317158918.

This PR adds three route and handler options that let a route opt out of the global response processing:

  • allow_fields: when false, the _fields parameter does not filter the response data.
  • allow_embed: when false, the _embed parameter does not embed linked resources. The links are still added as _links.
  • allow_links: when false, the response links are not added to the response data as _links.

All three default to true. A handler option takes precedence over the route option of the same name, as with allow_batch. The new WP_REST_Server::is_response_option_enabled() method reads them from the matched route and handler. The options apply to served, enveloped and preloaded requests.

register_rest_route(
        'my-ns/v1',
        '/run',
        array(
                'methods'             => 'GET',
                'callback'            => 'my_callback',
                'permission_callback' => '__return_true',
                'allow_fields'        => false,
                'allow_embed'         => false,
                'allow_links'         => false,
        )
);

This lets a route return its data unchanged, e.g. the abilities run endpoint, whose result follows the ability's output schema and can be an object, a list or a scalar value. ​https://github.com/WordPress/wordpress-develop/pull/14547 uses these options for that endpoint.

Drafted with AI assistance and reviewed by me.

Testing

Verify unit tests are passing:

npm run test:php -- --filter 'Tests_REST_Server' --group 66267

​@jorgefilipecosta commented on ​PR #14547:


4 weeks ago
#28

Could we let controllers explicitly opt out of _fields filtering, _embed processing, and response link injection?

Hi @gziolo, Currently there is no way to opt out, following your feedback I'm proposing it at ​https://github.com/WordPress/wordpress-develop/pull/14671.

This ticket was mentioned in ​PR #14672 on ​WordPress/wordpress-develop by ​@ravipatel.


4 weeks ago
#29

Summary

_wp_json_schema_matches_type() was added in r64592 / ba4c6de1c7 (#66267) and is currently only tested indirectly through wp_prepare_json_value_for_client(). This PR adds direct tests for it.

The new data provider covers:

  • whether the schema's type allows the requested type
  • a value with the right type that fails a constraint (e.g. minItems)
  • a schema with no type, anyOf or oneOf (returns false)
  • anyOf with a matching branch
  • anyOf where the type is in one branch and the valid value is in another (must be rejected, as the docblock says)
  • oneOf with no branch of the requested type, and with two matching branches
  • anyOf and oneOf together (both must match)
  • untyped branches taking the parent's type, when it allows the request and when it doesn't
  • a schema made only of invalid (non-array) branches
  • anyOf nested inside oneOf
  • object requested for an empty array

The patch only adds tests. The helper's code is unchanged.

Notes for reviewers

Two behaviours came up while writing these. Neither is introduced by r64592.

  1. The helper skips non-array branches only while checking them. Its final call to rest_validate_value_from_schema() still gets the full schema, so an invalid string branch next to a matching array branch causes a TypeError in rest-api.php. rest_find_any_matching_schema() fails the same way on such a schema, so I didn't add that case.
  2. rest_is_object() treats a PHP list such as array( 'a' ) as a valid object. So oneOf with an object branch next to an array branch can count as two matches.

Testing

  • phpunit --group json-schema: OK (92 tests, 149 assertions)
  • phpunit -c tests/phpunit/multisite.xml --group json-schema: OK (92 tests, 149 assertions)
  • phpcs tests/phpunit/tests/json-schema.php: no issues

Use of AI Tools

I used Claude Code (Anthropic) to help write the test cases and this description. I reviewed every case, ran the tests locally, and checked the results.

#30 @ravipatel
4 weeks ago

Follow-up to [64592]: ​https://github.com/WordPress/wordpress-develop/pull/14672 adds direct tests for _wp_json_schema_matches_type(), which until now was only tested indirectly through wp_prepare_json_value_for_client().

The new data provider covers explicit and inherited types, anyOf/oneOf branches, nested combining keywords, and the case where the type and a valid value are in different branches. The PR only adds tests.

Two notes on existing REST validation behaviour came up while writing them. They are in the PR description.

Tests pass on single site and multisite (--group json-schema, 92 tests), and phpcs is clean.

​@gziolo commented on ​PR #14671:


4 weeks ago
#31

Thanks for picking this up so quickly, @jorgefilipecosta! The opt-out works well, and all checks pass on my side. I spent some time going back and forth with Claude and Codex on the API shape, trying to find the easiest contract to use. Here's where I ended up.

What if we combine the three options into one response_processing option? The main use case is an endpoint like ability execution. It owns its output schema and just needs WordPress to leave its data alone, whether the result is an object, a list or a scalar.

// Turn off all processing.
'response_processing' => false,

// Or turn off only some parts.
'response_processing' => array(
        'fields' => false,
        'embed'  => false,
        'links'  => false,
),

How it could work

  • No option means nothing changes.
  • Settings combine one feature at a time: handler, then route, then the core default. A false at either level turns off the whole group.
  • Turning off links also turns off embedding, since embedding needs links.
  • It only covers _fields, _embed and adding _links. Auth, permissions, status codes, headers and JSON encoding work as before. We still need to figure out how _envelope fits in.
  • When processing is off, the endpoint's own keys (like its own _links or _embedded) stay untouched.

Where it should apply

  • Work the setting out in one place and use it everywhere these features run. That includes controller field selection (get_fields_for_response()) and collections, not only the final output. Controllers can already read the matched handler with $request->get_attributes().
  • Cached responses too. Right now is_response_option_enabled() returns true when a response has no matched route, so a response returned early from rest_pre_dispatch gets processed again.
  • rest_preload_api_request() casts the data with (array), so "ok" becomes ["ok"]. A preload test with a scalar would catch it.
  • get_data_for_route() could list the setting for each endpoint, the way it does for allow_batch, so clients can see it in the index.

Nice to have

rest_filter_response_fields() and response_to_data() could skip their work when the data isn't an array. Then routes that forget to opt out still don't break.

That gives abilities a simple "keep my data as is" switch, and other routes can still turn off single features. Happy to help with any of it!

​@jorgefilipecosta commented on ​PR #14671:


4 weeks ago
#32

Hi @gziolo,

We still need to figure out how _envelope fits in.

I think it does not need an option. It only wraps the response in body, status and headers and does not touch the data, so when processing is off the body is the data as returned. There is a test for that case, and the batch endpoint relies on the same wrapper for every sub-response, so I guess a route should not be able to turn it off.

​@gziolo commented on ​PR #14547:


4 weeks ago
#33

I approved ​https://github.com/WordPress/wordpress-develop/pull/14671, so let's commit it, and I will finish reviewing this one. Currently, it contains changes from both.

​@gziolo commented on ​PR #14672:


4 weeks ago
#34

Thanks for the PR and the effort to improve test coverage!

I’d prefer to test the more complex cases through wp_prepare_json_value_for_client(), checking the resulting JSON ([] or {}). This protects the public behavior even if we change the internal helper later.

Could we:

  • Add the missing oneOf multiple-match and combined anyOf/oneOf cases to the existing public-function tests.
  • Keep three basic tests for _wp_json_schema_matches_type(): an accepted type, an excluded type, and a value that fails validation through the requested type.
  • Reuse the existing coverage for nesting and type inheritance instead of adding duplicate cases.

This would keep the tests focused while still giving the internal helper some direct coverage.

​@ravipatel commented on ​PR #14672:


4 weeks ago
#35

Thanks @gziolo, that makes sense. Updated in 801717e91f:

  • Added the two cases to data_wp_prepare_json_value_for_client(), asserting the JSON output: an array branch whose oneOf matches more than once now gives {}, and a branch whose anyOf allows an array but whose oneOf doesn't gives []. Both fail if _wp_json_schema_matches_type() stops checking oneOf.
  • Reduced the direct helper tests to the three basic cases: accepted type, excluded type, and a value that fails validation through the requested type.
  • Removed the cases already covered by the existing nesting and type-inheritance tests.

--group json-schema passes on single site and multisite.

​@gziolo commented on ​PR #14671:


4 weeks ago
#36

Great refactoring with adding $data_processing directly to the response object 👍🏻

#37 @jorgefilipecosta
4 weeks ago

In 64689:

REST API: Let routes turn off _fields, _embed and response links.

Add a data_processing option to REST routes and route handlers, so a route can serve its response data as returned. The option is false to turn off every feature, or an array with any of the fields, embed and links keys. Every feature is on by default, the handler setting applies over the route setting feature by feature, and turning off links also turns off embed.
The settings are resolved once, when the request is matched, and stored on the request attributes, the matched handler and the response, where rest_filter_response_fields(), WP_REST_Controller::get_fields_for_response() and WP_REST_Server::response_to_data() read them. They apply to served, enveloped, batched and preloaded requests, and to responses returned by the rest_pre_dispatch filter. The index lists the settings of endpoints that turn a feature off.
Response data that is not an array is now served as returned even without the option: _fields leaves scalars and objects alone and keeps list items that are not arrays, links are not added to them unless the object implements ArrayAccess, and rest_preload_api_request() no longer casts preloaded data to an array.
This lets endpoints that own their output schema, such as the abilities run endpoint, return objects, lists and scalar values unchanged.

Props jorgefilipecosta, gziolo.
See #66267.
Fixes #66372.

#38 @gziolo
3 weeks ago

In 64728:

Tests: Expand JSON Schema value preparation coverage

Test nested oneOf schemas with multiple matching branches and combined anyOf/oneOf schemas through wp_prepare_json_value_for_client(), asserting the resulting JSON representation. Add three basic tests for _wp_json_schema_matches_type() while retaining the existing coverage for nesting and type inheritance.

Follow-up to [64592].

Props ravipatel, gziolo.
See #66267.

​@ravipatel commented on ​PR #14672:


3 weeks ago
#40

Thanks for the review and the commit, @gziolo!

​@gziolo commented on ​PR #14547:


3 weeks ago
#41

@jorgefilipecosta, do we still want to include this in WordPress 7.2?

​@jorgefilipecosta commented on ​PR #14547:


3 weeks ago
#42

Hi @gziolo, yes, I think so. The PR was rebased and is now only the run controller change on top of https://core.trac.wordpress.org/changeset/64689; without it core/settings-get still returns [] when no setting matches.

#43 @jorgefilipecosta
3 weeks ago

In 65072:

Abilities API: Encode empty object results as JSON objects.

The run endpoint prepared only associative array results for JSON clients, so an empty array returned for an object output schema, such as the core/settings-get result when no setting matches, was encoded as [] and failed output validation in JSON clients. Prepare every result, including root results, lists, object and JsonSerializable results, so empty objects are encoded as {} while arrays stay arrays.
Register the run endpoint with the data_processing route option set to false, so the _fields and _embed parameters and response links leave the result unchanged and it follows the ability's output schema whether it is an object, an array, or a scalar value. The REST API client fixture lists the disabled processing for the run endpoint.

Follow-up to [64311], [64592], [64689].

Props jorgefilipecosta, gziolo.
See #66267.

#44 @gziolo
2 weeks ago

  • Keywords needs-dev-note added

Dev note: Fixing empty objects in JSON in WordPress 7.2

WordPress 7.2 fixes cases where empty objects were encoded as JSON arrays in schemas and ability results. The new wp_prepare_json_value_for_client() function uses the schema to preserve the intended JSON type.

PHP commonly uses array() for both empty objects and empty arrays. JSON encodes it as [], even when the schema declares an object. This can cause clients to reject an otherwise valid result.

Preparing values for JSON

The new function converts empty PHP arrays to objects where the schema requires it:

$schema = array( 'type' => 'object' );
$value  = wp_prepare_json_value_for_client( array(), $schema );

echo wp_json_encode( $value );
// {}

Preparation also applies to nested properties and array items. For example, an object-valued settings property changes from:

{"settings":[]}

to:

{"settings":{}}

Empty arrays remain [] when a matching schema allows arrays. Matching anyOf and oneOf branches are also considered. If both representations are allowed, an empty PHP array stays an array.

This function prepares values for JSON encoding. It does not insert missing defaults or perform full JSON Schema validation.

Where this applies

  • wp_prepare_json_schema_for_client() now prepares existing default values according to their schemas, including nested defaults.
  • The WordPress AI Client prepares ability results using the ability's output schema.
  • The Abilities REST run endpoint prepares nested values in associative array results. Support for root empty objects and objects inside top-level lists is being handled separately.
  • REST view configurations and entity fields use the same helper for schema-based value preparation.

Direct calls to WP_Ability::execute() keep their PHP return values. JSON preparation happens when results are prepared for clients.

Guidance for developers

Declare object or array explicitly in your schemas so clients receive the intended JSON structure.

Custom integrations that encode ability results can prepare successful results before encoding:

$result = $ability->execute( $input );

if ( ! is_wp_error( $result ) ) {
    $result = wp_prepare_json_value_for_client(
        $result,
        $ability->get_output_schema()
    );

    $json = wp_json_encode( $result );
}

Clients should expect an empty JSON object where the schema declares an object, rather than relying on the previous [] representation.

This ticket was mentioned in ​Slack in #core-ai by jeffpaul. ​View the logs.


6 days ago

Note: See TracTickets for help on using tickets.