This package is a Golang implementation of JSON Canonicalization Scheme ("JCS"), aka RFC 8785. This package complies with all test data supplied by the JCS spec authors.
To install this package, run:
go get github.com/ucarion/jcs
This package works on the standard JSON-like Golang data structures, namely:
bool
, for JSON booleansfloat64
, for JSON numbersstring
, for JSON strings[]interface{}
, for JSON arraysmap[string]interface{}
, for JSON objectsnil
for JSON nullThese are the types of data you get out of json.Unmarshal
by default. So, to
encode some existing JSON data into canonical format, you can do something like:
import (
"encoding/json"
"fmt"
"github.com/ucarion/jcs"
)
fn main() {
input := `{"z": [1, 2, 3], "a": "foo" }`
var v interface{}
if err := json.Unmarshal([]byte(input), &v); err != nil {
panic(err)
}
// See note about error handling below
out, _ := jcs.Format(v)
fmt.Println(out)
}
If you have an existing buffer you'd prefer to output to instead, use
jcs.Append
instead of jcs.Format
:
var buf []byte
// See note about error handling below
buf, _ = jcs.Append(buf, &input)
You can, of course, pass your own data structures to Format
or Append
, but
note that you will get an error if you use a type other than those described
above.
See the documentation for more details,
but note that Append
and Format
may return errors if any of the following are true:
NaN
.If your inputted data is an interface{}
from json.Unmarshal
, then you do not
need to worry about errors from this package. Otherwise, you will need to
somehow ensure you don't pass unsupported data, or otherwise add support for an
error from this package.
A note on testing in this package: the TestFormatFloat100M
test in this
package is disabled by default, because it takes too long time and compute power
to run by default. Plus, the required test file takes 3.8G of disk space.
If you would like to thoroughly test the encoding of float64
values in this
package, download es6testfile100m.txt
from the link in the testdata
dir of
the JCS repo. When running tests, pass JCS_TEST_100M=1
, for
instance:
JCS_TEST_100M=1 go test ./... -v
Passing -v
will show you a progress indication once for every million tests
run.