canonicalJson top-level constant

Codec<Object?, List<int>> const canonicalJson

Encode/decode canonical JSON.

Encoding does not support floating-point numbers (including -0.0). Encoding the same JSON value always produces the same representation. This is useful when signing JSON objects.

Decoding decodes the value to List<Object>, Map<String,Object>, int, bool, String and null similar to json.Decode. This also validates that the bytes given is a valid canonical JSON encoding, throwing InvalidCanonicalJsonException if this is not the case. Using the canonicalJson.decode method ensures that the value returned could not have a different encoding producing the same value. This is useful when validating signed JSON objects.

Example

import 'package:canonical_json/canonical_json.dart';

void main() {
  // Encode a message
  final bytes = canonicalJson.encode({
    'from': 'alice',
    'message': 'Hi Bob',
  });
  final hash = sha256(bytes); // using a sha256 from some library...

  // Decode message
  try {
    final msg = canonicalJson.decode(bytes);
    if (!fixedTimeEqual(sha256(canonicalJson.encode(msg)), bytes)) {
      print('Expected a different hash!');
    }
    print(msg['message']);
  } on InvalidCanonicalJsonException {
    print('Message was not canonical JSON!');
  }
}

Implementation

const Codec<Object?, List<int>> canonicalJson = CanonicalJsonCodec();