LoginSignup
28
16

More than 5 years have passed since last update.

null だけの JSON は合法か?

Last updated at Posted at 2016-04-23

TL;DR

  • JSON の規格は RFC 4627RFC 7159 があって、 7159 によって 4627 は Obsolete とされている
  • 4627 はトップレベルには object もしくは array のみ置けるとしているので null だけの JSON は非合法
  • 7159 ではトップレベルには value があれば良いことになったので合法
  • Ruby の JSON モジュールは前者準拠(?) のようで JSON.parse('null') は例外を発生させる (追記あり)

発端

Ruby の JSON モジュールにこういう JSON を食わせると、コケて例外が上がってきてしまう。

JSON.parse("null") #=> JSON::ParserError

一方、他の JSON 実装である Oj や、 Node.js, Chrome では問題なく nil/null にパースされる。

> JSON.parse("null")
null

これは困った。

JSON の規格

JSON の規格は ECMA と RFC で定義されている。 RFC には 4627 と 7159 があり、前者は後者によって deprecated とされているので、現在の標準は RFC 7159 ということになる。それぞれ、トップレベルにおいて許される表現をこう定義している:

ECMA 404

A JSON text is a sequence of tokens formed from Unicode code points that conforms to the JSON value
grammar.

とされている。 value は object/array/number/string/true/false/null のいずれかのことであり、従って null だけの JSON は合法である。

RFC 4627

A JSON text is a serialized object or array.

  JSON-text = object / array

とされている。 null は object でも array でもないので、非合法だ。

RFC 7159

A JSON text is a sequence of tokens.  The set of tokens includes six
structural characters, strings, numbers, and three literal names.

A JSON text is a serialized value. Note that certain previous
specifications of JSON constrained a JSON text to be an object or an
array.  Implementations that generate only objects or arrays where a
JSON text is called for will be interoperable in the sense that all
implementations will accept these as conforming JSON texts.

   JSON-text = ws value ws

とされている。 null だけの JSON は合法である。

結論

というわけで null だけで構成される JSON は現在では合法で、 Ruby の JSON モジュールが古い規格に従っているだけのことであった

追記: Ruby の JSON モジュールについて

flori/json 2.0.0 で RFC 7159 準拠になったようです。 JSON.parse("null") も無事 nil を返すようになりました。

28
16
1

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
28
16