Encodes a dictionary key - a key can only be a string in std JSON
354084
def _encode_key(self, obj):
        """"""

        if obj.__class__ is str:
            return self._encode_str(obj)

        if obj.__class__ is UUID:
            return '"' + str(obj) + '"'

        # __mm_serialize__ is called before any isinstance checks (but after exact type checks)
        try:
            sx_encoder = obj.__mm_serialize__
        except AttributeError:
            pass
        else:
            try:
                data = sx_encoder()
            except NotImplementedError:
                pass
            else:
                return self._encode_key(data)

        if isinstance(obj, UUID):
            return '"' + str(obj) + '"'

        if isinstance(obj, str):
            return self._encode_str(obj)

        # if everything else failed try the default() method and re-raise any TypeError
        # exceptions as more specific "not a valid dict key" TypeErrors
        try:
            value = self.default(obj)
        except TypeError:
            raise TypeError('{!r} is not a valid dictionary key'.format(obj))

        return self._encode_key(value)
430620
public static void writeJSONKV(String key, Object value, Appendable out, JSONStyle compression) throws IOException {
		if (key == null)
			out.append("null");
		else if (!compression.mustProtectKey(key))
			out.append(key);
		else {
			out.append('"');
			JSONValue.escape(key, out, compression);
			out.append('"');
		}
		out.append(':');
		if (value instanceof String)
			compression.writeString(out, (String) value);
		else
			JSONValue.writeJSONString(value, out, compression);
	}
349104
def serialize_dict_keys(d, prefix=""):
    
    keys = []
    for k, v in d.items():
        fqk = '{}{}'.format(prefix, k)
        keys.append(fqk)
        if isinstance(v, dict):
            keys.extend(serialize_dict_keys(v, prefix="{}.".format(fqk)))

    return keys
589117
def _encode_dict(d):
    """"""
    def enc(x):
        if isinstance(x, six.text_type):
            return x.encode(_ENCODING)
        else:
            return x

    return dict((enc(k), enc(v)) for k, v in six.iteritems(d))
1140266
def _decode_embedded_dict(src):
    '''
    
    '''
    output = {}
    for key, val in six.iteritems(src):
        if isinstance(val, dict):
            val = _decode_embedded_dict(val)
        elif isinstance(val, list):
            val = _decode_embedded_list(val)  # pylint: disable=redefined-variable-type
        elif isinstance(val, bytes):
            try:
                val = val.decode()
            except UnicodeError:
                pass
        if isinstance(key, bytes):
            try:
                key = key.decode()
            except UnicodeError:
                pass
        output[key] = val
    return output
356556
def encode_dict(data, encoding=None, errors='strict', keep=False,
                preserve_dict_class=False, preserve_tuples=False):
    '''
    
    '''
    rv = data.__class__() if preserve_dict_class else {}
    for key, value in six.iteritems(data):
        if isinstance(key, tuple):
            key = encode_tuple(key, encoding, errors, keep, preserve_dict_class) \
                if preserve_tuples \
                else encode_list(key, encoding, errors, keep,
                                 preserve_dict_class, preserve_tuples)
        else:
            try:
                key = salt.utils.stringutils.to_bytes(key, encoding, errors)
            except TypeError:
                # to_bytes raises a TypeError when input is not a
                # string/bytestring/bytearray. This is expected and simply
                # means we are going to leave the value as-is.
                pass
            except UnicodeEncodeError:
                if not keep:
                    raise

        if isinstance(value, list):
            value = encode_list(value, encoding, errors, keep,
                                preserve_dict_class, preserve_tuples)
        elif isinstance(value, tuple):
            value = encode_tuple(value, encoding, errors, keep, preserve_dict_class) \
                if preserve_tuples \
                else encode_list(value, encoding, errors, keep,
                                 preserve_dict_class, preserve_tuples)
        elif isinstance(value, Mapping):
            value = encode_dict(value, encoding, errors, keep,
                                preserve_dict_class, preserve_tuples)
        else:
            try:
                value = salt.utils.stringutils.to_bytes(value, encoding, errors)
            except TypeError:
                # to_bytes raises a TypeError when input is not a
                # string/bytestring/bytearray. This is expected and simply
                # means we are going to leave the value as-is.
                pass
            except UnicodeEncodeError:
                if not keep:
                    raise

        rv[key] = value
    return rv
3708
def encode(cls, value):
        
        try:
            coerced = list(value)
            if coerced == value:
                return json.dumps(coerced).encode(cls._encoding)
        except TypeError:
            pass

        raise InvalidValue('not a list')
812109
def _encoder(self, obj):
        
        return {'__class__': obj.__class__.__name__,
                'ident': obj.ident,
                'group': obj.group,
                'name': obj.name,
                'ctype': obj.ctype,
                'pytype': obj.pytype,
                'access': obj.access}
        raise TypeError(repr(obj) + ' is not JSON serializable')
1295808
def __enforce_only_strings_dict(dictionary):
    '''
    
    '''
    ret = {}

    for key, value in iteritems(dictionary):
        ret[six.text_type(key)] = six.text_type(value)

    return ret
1212105
function encodeAsString(obj) {
  var str = '';
  var nsp = false;

  // first is type
  str += obj.type;

  // attachments if we have them
  if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
    str += obj.attachments;
    str += '-';
  }

  // if we have a namespace other than `/`
  // we append it followed by a comma `,`
  if (obj.nsp && '/' != obj.nsp) {
    nsp = true;
    str += obj.nsp;
  }

  // immediately followed by the id
  if (null != obj.id) {
    if (nsp) {
      str += ',';
      nsp = false;
    }
    str += obj.id;
  }

  // json data
  if (null != obj.data) {
    if (nsp) str += ',';
    str += json.stringify(obj.data);
  }

  debug('encoded %j as %s', obj, str);
  return str;
}
1305560
def translate_key_val(val, delimiter='='):
    '''
    
    '''
    if isinstance(val, dict):
        return val
    val = translate_stringlist(val)
    new_val = {}
    for item in val:
        try:
            lvalue, rvalue = split(item, delimiter, 1)
        except (AttributeError, TypeError, ValueError):
            raise SaltInvocationError(
                '\'{0}\' is not a key{1}value pair'.format(item, delimiter)
            )
        new_val[lvalue] = rvalue
    return new_val
959760
def _key_from_json(self, data):
        
        key = Key()
        key.algorithm = data["Algorithm"]
        key.cipher_mode = data["CipherMode"]
        key.expiration = datetime.strptime(data["Expiration"].split(".")[0],
                                           "%Y-%m-%dT%H:%M:%S")
        key.key_id = data["ID"]
        key.key = data["Key"]
        key.size = data["KeySize"]
        key.url = data["KeyUrl"]
        return key
668662
def serialize_dict_keys(d, prefix=""):
    
    keys = []
    for k, v in d.iteritems():
        fqk = '%s%s' % (prefix, k)
        keys.append(fqk)
        if isinstance(v, dict):
            keys.extend(serialize_dict_keys(v, prefix="%s." % fqk))

    return keys
957930
def _encode(cls, value):
        """"""

        value = json.dumps(value)
        return cls._ENC_RE.sub(lambda x: '%%%2x' % ord(x.group(0)), value)
261718
def _to_key(d):
        """"""
        as_str = json.dumps(d, sort_keys=True)
        return as_str.replace('"{{', '{{').replace('}}"', '}}')
824262
def _encode(self, obj):
        

        if self._use_hook:
            obj = self.encode_hook(obj)

        # first try simple strict checks

        _objtype = obj.__class__

        if _objtype is str:
            return self._encode_str(obj)

        if _objtype is bool:
            if obj:
                return 'true'
            else:
                return 'false'

        if _objtype is int or _objtype is float:
            return self._encode_numbers(obj)

        if _objtype is list or _objtype is tuple:
            return self._encode_list(obj)

        if obj is None:
            return 'null'

        if _objtype is dict or obj is OrderedDict:
            return self._encode_dict(obj)

        if _objtype is UUID:
            return '"' + str(obj) + '"'

        if _objtype is Decimal:
            return '"' + str(obj) + '"'

        # For all non-std types try __mm_json__ and then __mm_serialize__ before any isinstance
        # checks

        try:
            sx_json_data = obj.__mm_json__
        except AttributeError:
            pass
        else:
            try:
                data = sx_json_data()
            except NotImplementedError:
                pass
            else:
                if isinstance(data, bytes):
                    return data.decode('utf-8')
                else:
                    return self._encode_str(data, escape_quotes=False)
        try:
            sx_encoder = obj.__mm_serialize__
        except AttributeError:
            pass
        else:
            try:
                data = sx_encoder()
            except NotImplementedError:
                pass
            else:
                return self._encode(data)

        # do more in-depth class analysis

        if isinstance(obj, UUID):
            return '"' + str(obj) + '"'

        if isinstance(obj, str):
            return self._encode_str(obj)

        if isinstance(obj, (list, tuple, set, frozenset, Set)):
            return self._encode_list(obj)

        if isinstance(obj, Sequence) and not isinstance(obj, (bytes, bytearray)):
            return self._encode_list(obj)

        if isinstance(obj, (dict, OrderedDict, Mapping)):
            return self._encode_dict(obj)

        # note: number checks using isinstance should come after True/False checks
        if isinstance(obj, Number):
            return self._encode_numbers(obj)

        if isinstance(obj, (date, time)):
            return '"' + obj.isoformat() + '"'

        return self._encode(self.default(obj))
218495
def _convert_dict_to_json(array):
    
    return json.dumps(
        array,
        skipkeys=False,
        allow_nan=False,
        indent=None,
        separators=(",", ":"),
        sort_keys=True,
        default=lambda o: o.__dict__,
    )