LoginSignup
22
19

More than 5 years have passed since last update.

Rubyでnullや数値だけからなるjsonをパースする方法

Posted at

Rubyで標準ライブラリを用いてjsonをパースする際、null数値だけをパースすると例外が投げられます

pry(main)> require 'json'
=> true

pry(main)> JSON.parse('null')
JSON::ParserError: 757: unexpected token at 'null'
from ~/.rbenv/versions/2.1.1/lib/ruby/2.1.0/json/common.rb:155:in `parse`

pry(main)> JSON.parse('33')
JSON::ParserError: 757: unexpected token at '33'
from ~/.rbenv/versions/2.1.1/lib/ruby/2.1.0/json/common.rb:155:in `parse`

もはやjsonじゃ無い気もするので自然な挙動ではありますが、quirks_modeというオプションをtrueに設定してやると良い感じに変換してくれる様です。

pry(main)> JSON.parse('null', quirks_mode: true)
=> nil

pry(main)> JSON.parse('33', quirks_mode: true)
=> 33

参考
https://github.com/flori/json/issues/131
http://stackoverflow.com/questions/3552328/nil-to-json-cannot-be-parsed-back-to-nil

22
19
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
22
19