github.com/lusis/distribution@v2.0.1+incompatible/docs/spec/json.md (about) 1 <!--GITHUB 2 page_title: Docker Distribution JSON Canonicalization 3 page_description: Explains registry JSON objects 4 page_keywords: registry, service, images, repository, json 5 IGNORES--> 6 7 8 # Docker Distribution JSON Canonicalization 9 10 To provide consistent content hashing of JSON objects throughout Docker 11 Distribution APIs, the specification defines a canonical JSON format. Adopting 12 such a canonicalization also aids in caching JSON responses. 13 14 ## Rules 15 16 Compliant JSON should conform to the following rules: 17 18 1. All generated JSON should comply with [RFC 19 7159](http://www.ietf.org/rfc/rfc7159.txt). 20 2. Resulting "JSON text" shall always be encoded in UTF-8. 21 3. Unless a canonical key order is defined for a particular schema, object 22 keys shall always appear in lexically sorted order. 23 4. All whitespace between tokens should be removed. 24 5. No "trailing commas" are allowed in object or array definitions. 25 26 ## Examples 27 28 The following is a simple example of a canonicalized JSON string: 29 30 ```json 31 {"asdf":1,"qwer":[],"zxcv":[{},true,1000000000,"tyui"]} 32 ``` 33 34 ## Reference 35 36 ### Other Canonicalizations 37 38 The OLPC project specifies [Canonical 39 JSON](http://wiki.laptop.org/go/Canonical_JSON). While this is used in 40 [TUF](http://theupdateframework.com/), which may be used with other 41 distribution-related protocols, this alternative format has been proposed in 42 case the original source changes. Specifications complying with either this 43 specification or an alternative should explicitly call out the 44 canonicalization format. Except for key ordering, this specification is mostly 45 compatible. 46 47 ### Go 48 49 In Go, the [`encoding/json`](http://golang.org/pkg/encoding/json/) library 50 will emit canonical JSON by default. Simply using `json.Marshal` will suffice 51 in most cases: 52 53 ```go 54 incoming := map[string]interface{}{ 55 "asdf": 1, 56 "qwer": []interface{}{}, 57 "zxcv": []interface{}{ 58 map[string]interface{}{}, 59 true, 60 int(1e9), 61 "tyui", 62 }, 63 } 64 65 canonical, err := json.Marshal(incoming) 66 if err != nil { 67 // ... handle error 68 } 69 ``` 70 71 To apply canonical JSON format spacing to an existing serialized JSON buffer, one 72 can use 73 [`json.Indent`](http://golang.org/src/encoding/json/indent.go?s=1918:1989#L65) 74 with the following arguments: 75 76 ```go 77 incoming := getBytes() 78 var canonical bytes.Buffer 79 if err := json.Indent(&canonical, incoming, "", ""); err != nil { 80 // ... handle error 81 } 82 ```