[wp-trac] [WordPress Trac] #51159: Let's expand our context specific escaping methods for wp_json_encode().
WordPress Trac
noreply at wordpress.org
Tue Sep 30 16:11:06 UTC 2025
#51159: Let's expand our context specific escaping methods for wp_json_encode().
-------------------------+-------------------------------------------------
Reporter: whyisjake | Owner: (none)
Type: enhancement | Status: new
Priority: normal | Milestone: Awaiting Review
Component: Security | Version:
Severity: normal | Resolution:
Keywords: | Focuses: javascript, template, coding-
| standards
-------------------------+-------------------------------------------------
Comment (by jonsurrell):
I've gotten feedback many times that a specific function should exist for
JSON data inside script tags. It's too hard to remember which flags to use
when, and there's no additional escaping to rely on. I tend to agree after
seeing how widespread this issue is.
JSON in many other contexts has an additional layer of escaping that makes
the JSON encoding less important. For example, `esc_attr( json_encode(
$data ) )` is fine to use in attributes.[#mostly-fine 1]
JSON in script tags needs to remain as JSON. HTML character references are
not decoded inside script tags, so there's no additional layer of escaping
to rely on. The JSON encoding on its own should be sufficient to produce
safe HTML.
Would folks find it beneficial to have a function for JSON in script tags
like `wp_json_encode_for_script_tag()`?
-----
[=#mostly-fine '''1:'''] `esc_url()` will not "double escape" HTML
character references, so if the JSON contains the text `&` it will
remain unchanged and decode to a plain `&` in the attribute value instead
of being escaped as `&`. It's likely better to use an alternative
that always escapes, but `esc_url()` is sufficient for illustration.
--
Ticket URL: <https://core.trac.wordpress.org/ticket/51159#comment:4>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list