rails / jbuilder

Jbuilder: generate JSON objects with a Builder-style DSL
MIT License
4.34k stars 438 forks source link

Can't seem to render unescaped HTML in Jbuilder #542

Closed Rotario closed 1 year ago

Rotario commented 2 years ago

Hi, thanks for the work this is really useful! Although I can't seem to render html_safe strings out? This code runs but

Jbuilder.encode do |json|  
   json.html '<button>html</button>'.html_safe
end

Expected: {"html": "<button>html</button>"}

Actual: {\"html\":\"\\u003cbutton\\u003ehtml\\u003c/button\\u003e\"} I'm running Ruby 3.1.0 and Jbuilder 2.11.5

dancristianb commented 1 year ago

Hey @Rotario 👋 I believe this is intentional, under the hood Jbuilder.encode uses #to_json and with Rails 4+, activesupport by default overrides #to_json escaping html entities. You can find some extra details on why here:

  1. https://stackoverflow.com/questions/32318261/rails-why-to-json-is-escaping-html-entities
  2. https://stackoverflow.com/questions/17936318/why-does-to-json-escape-unicode-automatically-in-rails-4

I think the important part here is that the output is parsable and that's not an issue 👌

Screenshot 2022-11-11 at 15 28 29

This is a default I would not override, see https://brakemanscanner.org/docs/warning_types/cross_site_scripting_to_json/ 😀 That being said, if you really need to, you can by setting the config.active_support.escape_html_entities_in_json config false.

Rotario commented 1 year ago

Thanks for the information - I'll read up on it!