LoginSignup
8
6

More than 5 years have passed since last update.

RubyとRailsのto_jsonの違い

Posted at

概要

出力される JSON に含まれる文字の一部が、JavaScript の Unicode エスケープシーケンス に変換されているかされていないかが異なる。

Rails 側は、どういう仕様なんだろう?と思いました。

ruby -v
ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-darwin14]
irb
irb(main):001:0> require 'json'
=> true
irb(main):002:0> "<".to_json
=> "\"<\""
irb(main):003:0> { "<" => "<" }.to_json
=> "{\"<\":\"<\"}"
bundle exec rails --version
Rails 4.2.7
bundle exec rails console  
[1] pry(main)> "<".to_json
=> "\"\\u003c\""
[2] pry(main)> { "<" => "<" }.to_json
=> "{\"\\u003c\":\"\\u003c\"}"

結論

仕様だった。

          # Rails does more escaping than the JSON gem natively does (we
          # escape \u2028 and \u2029 and optionally >, <, & to work around
          # certain browser problems).
          ESCAPED_CHARS = {
            "\u2028" => '\u2028',
            "\u2029" => '\u2029',
            '>'      => '\u003e',
            '<'      => '\u003c',
            '&'      => '\u0026',
            }

コピペ元) https://github.com/rails/rails/blob/4-2-stable/activesupport/lib/active_support/json/encoding.rb#L39-L41

なお、引数で処理を変えれる よう。

補足) 何故調べたのか

HTML 内にある script タグに </script> が書かれると JS が壊れる 問題がふと気になって、Rails でテンプレート上で to_json した場合に大丈夫なのかな?というのを調べたからです。

ちゃんとしていました。

8
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
6