[wp-trac] [WordPress Trac] #43766: Update WP_Script::localize to be JSON standard compliant

WordPress Trac noreply at wordpress.org
Fri Apr 13 16:36:49 UTC 2018


#43766: Update WP_Script::localize to be JSON standard compliant
-----------------------------+-----------------------------
 Reporter:  jason_the_adams  |      Owner:  (none)
     Type:  defect (bug)     |     Status:  new
 Priority:  normal           |  Milestone:  Awaiting Review
Component:  Script Loader    |    Version:  4.9.5
 Severity:  normal           |   Keywords:  needs-patch
  Focuses:                   |
-----------------------------+-----------------------------
 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
 <?php
 wp_localize_script('test', 'testData', [
      'bool'  => true,
      'num'   => 5,
      'array' => [
         'bool'  => false,
         'num'   => 8
      ]
 ]);
 }}}

 {{{#!js
 // 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?

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/43766>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list