The data_type argument must be a Union.
        See json_compat_obj_decode() for argument descriptions.
766288
def decode_union_old(self, data_type, obj):
        
        val = None
        if isinstance(obj, six.string_types):
            # Union member has no associated value
            tag = obj
            if data_type.definition._is_tag_present(tag, self.caller_permissions):
                val_data_type = data_type.definition._get_val_data_type(tag,
                                                                        self.caller_permissions)
                if not isinstance(val_data_type, (bv.Void, bv.Nullable)):
                    raise bv.ValidationError(
                        "expected object for '%s', got symbol" % tag)
            else:
                if not self.strict and data_type.definition._catch_all:
                    tag = data_type.definition._catch_all
                else:
                    raise bv.ValidationError("unknown tag '%s'" % tag)
        elif isinstance(obj, dict):
            # Union member has value
            if len(obj) != 1:
                raise bv.ValidationError('expected 1 key, got %s' % len(obj))
            tag = list(obj)[0]
            raw_val = obj[tag]
            if data_type.definition._is_tag_present(tag, self.caller_permissions):
                val_data_type = data_type.definition._get_val_data_type(tag,
                                                                        self.caller_permissions)
                if isinstance(val_data_type, bv.Nullable) and raw_val is None:
                    val = None
                elif isinstance(val_data_type, bv.Void):
                    if raw_val is None or not self.strict:
                        # If raw_val is None, then this is the more verbose
                        # representation of a void union member. If raw_val isn't
                        # None, then maybe the spec has changed, so check if we're
                        # in strict mode.
                        val = None
                    else:
                        raise bv.ValidationError('expected null, got %s' %
                                                 bv.generic_type_name(raw_val))
                else:
                    try:
                        val = self.json_compat_obj_decode_helper(val_data_type, raw_val)
                    except bv.ValidationError as e:
                        e.add_parent(tag)
                        raise
            else:
                if not self.strict and data_type.definition._catch_all:
                    tag = data_type.definition._catch_all
                else:
                    raise bv.ValidationError("unknown tag '%s'" % tag)
        else:
            raise bv.ValidationError("expected string or object, got %s" %
                                     bv.generic_type_name(obj))
        return data_type.definition(tag, val)
1346535
function jsonit(data, type, setType) {
    if ('string' !== typeof data) {
      throw new JsonItError('Invalid JsonIt type: ' + typeof data)
    }
    var result = {}
    if (data.length > 0) {
      try {
        var colonPos = data.indexOf(':')
        var commaPos = data.indexOf(',')
        if (colonPos < 0 || (commaPos >= 0 && commaPos < colonPos)) {
          if (setType) defaultType = setType
          type = type || defaultType
          data = type + ':' + data
        }
        result = jsonic(data)
      } catch(err) {
        throw new JsonItError(err.message)
      }
    }
    return result
  }
802248
function getDataType(obj){
	var dataType = toClass.call( obj );
	dataType = dataType.split(' ')[1];
	dataType = dataType.substring(0, dataType.length-1);

	return dataType;
}
241566
def log_json_incompatible_types(obj):
    
    keys_to_explore = list(obj)
    while len(keys_to_explore) > 0:
        key = keys_to_explore.pop()
        if not isinstance(key, str):
            LOGGER.info(type(key))
        value = obj[key]
        if isinstance(value, dict):
            LOGGER.info("%s:", key)
            log_json_incompatible_types(value)
        elif not isinstance(value, JSON_TYPES):
            LOGGER.info("%s: %s", key, type(value))
        elif isinstance(value, (int, float)) and not isfinite(value):
            LOGGER.info("%s: %f", key, value)
472056
def _decode(obj):  # type: (bytes or str or unicode or object) -> unicode # noqa ignore=F821
    
    if obj is None:
        return u''
    if six.PY3 and isinstance(obj, six.binary_type):
        # transforms a byte string (b'') in unicode
        return obj.decode('latin1')
    elif six.PY3:
        # PY3 strings are unicode.
        return str(obj)
    elif isinstance(obj, six.text_type):
        # returns itself if it is unicode
        return obj
    else:
        # decodes pY2 string to unicode
        return str(obj).decode('utf-8')
927576
def pp_obj(obj, out_path=None, indent=4, sort_keys=False, ensure_ascii=False, default=None):
    
    rt = anyjson.dumps(obj, sort_keys=sort_keys, indent=indent, ensure_ascii=ensure_ascii,
                       separators=(',', ': '), default=default, namedtuple_as_object=False)
    # unicode_available
    if out_path is None:
        return rt
    else:
        with open(out_path, 'w') as out:
            out.write(rt)
293389
def decode_struct(self, data_type, obj):
        
        if obj is None and data_type.has_default():
            return data_type.get_default()
        elif not isinstance(obj, dict):
            raise bv.ValidationError('expected object, got %s' %
                                     bv.generic_type_name(obj))
        all_fields = data_type.definition._all_fields_
        for extra_permission in self.caller_permissions.permissions:
            all_extra_fields = '_all_{}_fields_'.format(extra_permission)
            all_fields = all_fields + getattr(data_type.definition, all_extra_fields, [])

        if self.strict:
            all_field_names = data_type.definition._all_field_names_
            for extra_permission in self.caller_permissions.permissions:
                all_extra_field_names = '_all_{}_field_names_'.format(extra_permission)
                all_field_names = all_field_names.union(
                    getattr(data_type.definition, all_extra_field_names, {}))

            for key in obj:
                if (key not in all_field_names and
                        not key.startswith('.tag')):
                    raise bv.ValidationError("unknown field '%s'" % key)
        ins = data_type.definition()
        self.decode_struct_fields(ins, all_fields, obj)
        # Check that all required fields have been set.
        data_type.validate_fields_only_with_permissions(ins, self.caller_permissions)
        return ins
539798
def value2json(obj, pretty=False, sort_keys=False, keep_whitespace=True):
    
    if FIND_LOOPS:
        obj = scrub(obj, scrub_text=_keep_whitespace if keep_whitespace else _trim_whitespace())
    try:
        json = json_encoder(obj, pretty=pretty)
        if json == None:
            Log.note(str(type(obj)) + " is not valid{{type}}JSON", type=" (pretty) " if pretty else " ")
            Log.error("Not valid JSON: " + str(obj) + " of type " + str(type(obj)))
        return json
    except Exception as e:
        e = Except.wrap(e)
        try:
            json = pypy_json_encode(obj)
            return json
        except Exception:
            pass
        Log.error("Can not encode into JSON: {{value}}", value=text_type(repr(obj)), cause=e)
1095082
def json_encoder_default(obj):
    
    if np is not None and hasattr(obj, 'size') and hasattr(obj, 'dtype'):
        if obj.size == 1:
            if np.issubdtype(obj.dtype, np.integer):
                return int(obj)
            elif np.issubdtype(obj.dtype, np.floating):
                return float(obj)

    if isinstance(obj, set):
        return list(obj)
    elif hasattr(obj, 'to_native'):
        # DatastoreList, DatastoreDict
        return obj.to_native()
    elif hasattr(obj, 'tolist') and hasattr(obj, '__iter__'):
        # for np.array
        return obj.tolist()

    return obj
753826
def repr2_json(obj_, **kwargs):
    
    import utool as ut
    kwargs['trailing_sep'] = False
    json_str = ut.repr2(obj_, **kwargs)
    json_str = str(json_str.replace('\'', '"'))
    json_str = json_str.replace('(', '[')
    json_str = json_str.replace(')', ']')
    json_str = json_str.replace('None', 'null')
    return json_str
1212090
function attrToJson(v, objectType) {

        var colValue;

        switch (objectType) {
            case "Text":
                colValue = v;
                break;
            case "DateTime":
            case "datetime": // For calculated columns, stored as datetime;#value
                // Dates have dashes instead of slashes: ows_Created="2009-08-25 14:24:48"
                colValue = dateToJsonObject(v);
                break;
            case "User":
                colValue = userToJsonObject(v);
                break;
            case "UserMulti":
                colValue = userMultiToJsonObject(v);
                break;
            case "Lookup":
                colValue = lookupToJsonObject(v);
                break;
            case "LookupMulti":
                colValue = lookupMultiToJsonObject(v);
                break;
            case "Boolean":
                colValue = booleanToJsonObject(v);
                break;
            case "Integer":
                colValue = intToJsonObject(v);
                break;
            case "Counter":
                colValue = intToJsonObject(v);
                break;
            case "MultiChoice":
                colValue = choiceMultiToJsonObject(v);
                break;
            case "Number":
            case "Currency":
            case "float": // For calculated columns, stored as float;#value
                colValue = floatToJsonObject(v);
                break;
            case "Calculated":
                colValue = calcToJsonObject(v);
                break;
            case "Attachments":
                colValue = attachmentsToJsonObject(v);
                break;
            case "URL":
                colValue = urlToJsonObject(v);
                break;
            case "JSON":
                colValue = jsonToJsonObject(v); // Special case for text JSON stored in text columns
                break;
            default:
                // All other objectTypes will be simple strings
                colValue = v;
                break;
        }
        return colValue;
    }
860508
def default(self, obj):
        
        if isinstance(obj, datetime):
            return obj.isoformat()

        if issubclass(obj.__class__, Enum.__class__):
            return obj.value

        to_json = getattr(obj, 'to_json', None)
        if to_json:
            out = obj.to_json()
            if issubclass(obj.__class__, Model):
                out.update({'__type': obj.__class__.__name__})

            return out

        return JSONEncoder.default(self, obj)
460260
def json_friendly(obj):
    """"""
    converted = True
    typename = get_full_typename(obj)

    if is_tf_tensor_typename(typename):
        obj = obj.eval()
    elif is_pytorch_tensor_typename(typename):
        try:
            if obj.requires_grad:
                obj = obj.detach()
        except AttributeError:
            pass  # before 0.4 is only present on variables

        try:
            obj = obj.data
        except RuntimeError:
            pass  # happens for Tensors before 0.4

        if obj.size():
            obj = obj.numpy()
        else:
            return obj.item(), True

    if np and isinstance(obj, np.ndarray):
        if obj.size == 1:
            obj = obj.flatten()[0]
        elif obj.size <= 32:
            obj = obj.tolist()
    elif np and isinstance(obj, np.generic):
        obj = obj.item()
    elif isinstance(obj, bytes):
        obj = obj.decode('utf-8')
    elif isinstance(obj, (datetime, date)):
        obj = obj.isoformat()
    else:
        converted = False
    if getsizeof(obj) > VALUE_BYTES_LIMIT:
        logger.warning("Object %s is %i bytes", obj, getsizeof(obj))

    return obj, converted
621888
function(db) {
		function call_func(data, fun, params) {
			try {

				// Parse data
				if(!(data && (data instanceof Array))) {
					throw new TypeError("First argument is not an array");
				}

				// Parse fun
				if(fun.substr(0, 8) === 'function') {
					// FIXME: This is the same code as in nor-function -- should be reused from there.
					fun = new Function('return (' + fun + ')')();
				} else {
					throw new TypeError("Second argument is not valid serialized function");
				}

				// Parse params
				if(!(params && (params instanceof Array))) {
					throw new TypeError("Third argument is not an array");
				}

				return fun.apply(undefined, [].concat(data).concat(params) );

			} catch (e) {
				plv8.elog(ERROR, e);
				return;
			}
		}
		return db.query('CREATE SCHEMA IF NOT EXISTS nopg')
			.query('CREATE OR REPLACE FUNCTION nopg.call_func(data json, fun json, params json) RETURNS json LANGUAGE plv8 STABLE AS ' + NoPg._escapeFunction(call_func, ["data", "fun", "params"]) );
	}
146817
def obj2unicode(obj):
    
    if isinstance(obj, unicode_type):
        return obj
    elif isinstance(obj, bytes_type):
        try:
            return unicode_type(obj, 'utf-8')
        except UnicodeDecodeError as strerror:
            sys.stderr.write("UnicodeDecodeError exception for string '%s': %s\n" % (obj, strerror))
            return unicode_type(obj, 'utf-8', 'replace')
    else:
        return unicode_type(obj)
935
def json_encode_default(obj):
    '''
    
    '''
    if isinstance(obj, (datetime, date)):
        result = dt2ts(obj)
    else:
        result = json_encoder.default(obj)
    return to_encoding(result)
1012195
def decode_nullable(self, data_type, obj):
        
        if obj is not None:
            return self.json_compat_obj_decode_helper(data_type.validator, obj)
        else:
            return None