WordPress.org

Make WordPress Core

Opened 3 months ago

Closed 3 months ago

#43766 closed defect (bug) (duplicate)

Update WP_Script::localize to be JSON standard compliant

Reported by: jason_the_adams Owned by:
Milestone: Priority: normal
Severity: normal Version:
Component: Script Loader Keywords:
Focuses: Cc:

Description

Presently, when using wp_localize_script all of the scalar values are cast as a string. This means that integers and booleans aren't what they should be. In fact, boolean values are "1" and "0". This means the JSON this function produces does not mean the JSON schema standard: https://spacetelescope.github.io/understanding-json-schema/reference/boolean.html

Another fun issue here is that the type casting isn't recursive, meaning arrays/objects containing scalar values are valid JSON. This means there's an inconsistency in the way values are produced. Consider the following:

<?php
wp_localize_script('test', 'testData', [
     'bool'  => true,
     'num'   => 5,
     'array' => [
        'bool'  => false,
        'num'   => 8
     ]
]);
// Yields the following JSON
{
    "bool": "1",
    "num": "5",
    "array": {
        "bool": false,
        "num": 8
    }
}

I understand that this was originally intended for localization, but this is hugely used by plugins and themes as a way of passing server data to the browser as JSON. It really should meet the JSON schema and work consistently.

I'll put a patch together shortly, but simply this should check for is_bool() and is_numeric prior to casting as a string and handling entities. And maybe it should be recursive so nested strings are also decoded?

Change History (2)

#1 @jason_the_adams
3 months ago

In the absence of a patch, I should have included that this is the culprit line of code: https://core.trac.wordpress.org/browser/tags/4.9/src/wp-includes/class.wp-scripts.php#L426

#2 @ocean90
3 months ago

  • Keywords needs-patch removed
  • Milestone Awaiting Review deleted
  • Resolution set to duplicate
  • Status changed from new to closed
  • Version 4.9.5 deleted

Thanks for the report, this issue is already being tracked in #25280.

Note: See TracTickets for help on using tickets.