Rails provides an excellent XML Builder by default to build RSS and ATOM feeds, but nothing to help you build complex and custom JSON data structures. JSON Builder is here to help.
val = "a\r\nb"
j = JSONBuilder::Compiler.generate { v val }
# => "{\"v\": \"a\r\nb\"}"
JSON.parse j
# => JSON::ParserError: 756: unexpected token at '{"v": "a
# b"}'
# from /home/di/.rvm/gems/ruby-1.9.2-p318@facewatch/gems/json_pure-1.6.6/lib/json/common.rb:148:in `parse'
# from /home/di/.rvm/gems/ruby-1.9.2-p318@facewatch/gems/json_pure-1.6.6/lib/json/common.rb:148:in `parse'
# from (irb):3
# from /home/di/.rvm/gems/ruby-1.9.2-p318@facewatch/gems/railties-3.0.12/lib/rails/commands/console.rb:44:in `start'
# from /home/di/.rvm/gems/ruby-1.9.2-p318@facewatch/gems/railties-3.0.12/lib/rails/commands/console.rb:8:in `start'
# from /home/di/.rvm/gems/ruby-1.9.2-p318@facewatch/gems/railties-3.0.12/lib/rails/commands.rb:23:in `<top (required)>'
# from script/rails:6:in `require'
# from script/rails:6:in `<main>'
puts val
# a
# b
# => nil
Gems:
json (1.6.6, 1.6.5) json_builder (3.1.0) json_pure (1.6.6, 1.6.5) multi_json (1.2.0, 1.1.0)
Workaround (I really don't like it!) for Rails: