[wp-trac] [WordPress Trac] #29910: esc_attr does not properly deal with json_encode

WordPress Trac noreply at wordpress.org
Thu Oct 9 17:54:33 UTC 2014


#29910: esc_attr does not properly deal with json_encode
----------------------------------+-----------------------------
 Reporter:  enej                  |      Owner:
     Type:  enhancement           |     Status:  new
 Priority:  normal                |  Milestone:  Awaiting Review
Component:  General               |    Version:  trunk
 Severity:  normal                |   Keywords:
  Focuses:  javascript, template  |
----------------------------------+-----------------------------
 Current doing something like esc_attr( json_encode( $data ) ); doesn't
 work properly.

 Since the input to json_encode() above can contain '"'. And for calls
 to json_encode() lacking the JSON_HEX_AMP option, that '"' is left
 unaltered.  Running '"' through esc_attr() also leaves it unaltered
 since esc_attr() does not double-encode.

 This means we end up with an attribute like


 {{{
 data-gallery="{"foo":"""}
 }}}


 which is interpreted by the browser as

 {{{
 {"foo":"""}
 }}}


 which results in a JSON decoded error.

 The preferred workaround is to include the JSON_HEX_AMP (and friends)
 options, but these are not available until 5.3.0.

 Alternatively, we can use _wp_specialchars( , , , true ) instead of
 esc_attr(), which will double-encode.

 Since we can't rely on JSON_HEX_AMP, we do both.

 I would like to see a function like


 {{{
 esc_json_encode( $data )
 }}}

 That you can use to encode json data and pass it to the html. I have
 included a file that includes a functions that does just that.

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


More information about the wp-trac mailing list