Make WordPress Core

Opened 10 years ago

Last modified 7 years ago

#29910 new enhancement

esc_attr does not properly deal with json_encode

Reported by: enej's profile enej 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)

esc_json_encode.php (567 bytes) - added by enej 10 years ago.
contains esc_json_encode function

Download all attachments as: .zip

Change History (6)

@enej
10 years ago

contains esc_json_encode function

#1 @mdawaffe
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.

#2 @enej
10 years ago

Another solution could be to detect if a json_encoded string is being passed into the esc_attr( ) function and if that is the case handle it differently from a string. This way no new function is created.

#3 @DrewAPicture
10 years ago

  • Component changed from General to Formatting

#4 @boonebgorges
10 years ago

  • Version trunk deleted

#5 @jbpaul17
7 years ago

  • Keywords needs-refresh added
Note: See TracTickets for help on using tickets.