LoginSignup
7
2

More than 5 years have passed since last update.

Go のプログラム内で JSON を比較しやすくする

Last updated at Posted at 2018-01-28

MarshalJSON() のテストを書くときに JSON 文字列同士を比較する際、どこが違うのかをわかりやすく表示するライブラリを作ってみた。

使用例

import (
    "testing"
    "github.com/Cside/jsondiff"
)

a := []byte(`{ "foo":1, "bar":2 }`)
b := []byte(`{ "foo":1, "bar":3 }`)

if diff := jsondiff.Diff(a, b); diff != "" {
    t.Errorf("two jsons are not equal. diff:\n%s", diff)
}

出力:

=== RUN   TestMain
--- FAIL: TestMain (0.00s)
        main_test.go:14: two jsons are not equal. diff:
                  {
                -   "bar": 2,
                +   "bar": 3,
                    "foo": 1
                  }
FAIL
exit status 1

特定の値を無視する

タイムスタンプとか、特定の値を比較の際に無視したくなることがある。その場合は diffopts.IgnorePath(paths []string) オプションを使う。

無視したい値はは JSON Pointer で指定する。

下記のテストはパスする。

import (
    "testing"
    "github.com/Cside/jsondiff"
    "github.com/Cside/jsondiff/diffopts"
)

a := []byte(`{ "foo": 1, "createdAt": 1517141881 }`)
b := []byte(`{ "foo": 1, "createdAt": 1528845681 }`)

if diff := jsondiff.Diff(a, b, diffopts.IgnorePaths([]string{"/createdAt"})); diff != "" {
    t.Errorf("two jsons are not equal. diff:\n%s", diff)
}

関連記事

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