LoginSignup
0
0

API Jsonリクエストでのnullについて

Last updated at Posted at 2023-11-07

JSON

RESTful APIが広く普及した現在、APIへのリクエスト・レスポンスはJSONを用いることが多いだろう。
JSONは数値や文字列、真偽値などの表現ができて便利だ。
しかし、JSONで表現する際に注意が必要なのはnull値である。

ここでは、以下のようなリクエストとレスポンスを考えることにする。(特に要素に意味はない。)

request
{
    "id" : 1,
    "date" : "2023-11-07",
    "member" : true,
    "name" : "John doe",
    "option" : null
}
response
{
    "update" : true
}

Null値について

1つ目のリクエストに、"option" : nullとあるが、JSONでnullを表現するには2通りの方法がある。

nullを明示的に指定する方法

Option 1
{
    "id" : 1,
    "date" : "2023-11-07",
    "member" : true,
    "name" : "John doe",
    "option" : null
}

nullである要素はそもそも削除する方法

Option 2
{
    "id" : 1,
    "date" : "2023-11-07",
    "member" : true,
    "name" : "John doe"
}

どっちがいいの?

大前提として、チーム内でルールが有るならそれに従ってほしい。

nullを明示的に指定する方法の利点

その要素がnull(値なし)であることが明確にわかる。

RFC8259においてnullも使用可能であると定められているから。

  1. Values
    A JSON value MUST be an object, array, number, or string, or one of the following three literal names:
    false
    null
    true

nullである要素はそもそも削除する方法の利点

リクエストペイロードの節約になる。

例えば、要素が10000個あるリクエストにおいて、すべての要素を明示的に指定すべきだろうか?

{
  "key1" : "hoge",
  "key2" : null,
  "key3" : "fuga",
  "key4" : null,
  "key5" : null,
  "key6" : null,
  "key7" : null,
  "key8" : null,
  "key9" : null,
  "key10" : null,
  "key11" : null,
  "key12" : null,
  "key13" : null,
  "key14" : null,
  ...
}

より、

{
  "key1" : "hoge",
  "key3" : fuga"
}

のほうがシンプルで良い。

Google JSON style guideではデータがない場合、項目を取り除くべきだと書いてあるから。

Consider removing empty or null values.
If a property is optional or has an empty or null value, consider dropping the property from the JSON, unless there's a strong semantic reason for its existence.

おまえはどうしたい?

私はnullである要素はそもそも削除する派閥です。

0
0
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
0
0