def _parse_canonical_code(doc):
    """Decode a JSON code to bson.code.Code."""
    for key in doc:
        if key not in ('$code', '$scope'):
            raise TypeError('Bad $code, extra field(s): %s' % (doc,))
    return Code(doc['$code'], scope=doc.get('$scope'))