Opened 10 years ago
Last modified 8 years ago
#29910 new enhancement
esc_attr does not properly deal with json_encode
Reported by: |
|
Owned by: | |
---|---|---|---|
Milestone: | Awaiting Review | Priority: | normal |
Severity: | normal | Version: | |
Component: | Formatting | Keywords: | needs-refresh |
Focuses: | javascript, template | Cc: |
Description
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.
Attachments (1)
Change History (6)
#1
@
10 years ago
The function name makes it seem like this is the correct function to use whenever outputting JSON. In reality, this technique is most useful when outputting JSON into an HTML attribute, as you describe with the data-gallery
example.
contains esc_json_encode function