Print JSON with indentation and colours
    :param obj: the object to print - can be a dict or a string
15720
def pretty_json(obj):
    
    if isinstance(obj, string_types):
        try:
            obj = json.loads(obj)
        except ValueError:
            raise ClientException("`obj` is not a json string")
    json_str = json.dumps(obj, sort_keys=True, indent=2)
    print(highlight(json_str, JsonLexer(), TerminalFormatter()))
565003
def dumps(obj):
    """"""
    return json.dumps(obj, indent=4, sort_keys=True, cls=CustomEncoder)
749170
def json_serialize(obj):
    
    if isinstance(obj, datetime):
        return obj.isoformat()

    if hasattr(obj, 'id'):
        return jsonify(obj.id)

    if hasattr(obj, 'name'):
        return jsonify(obj.name)

    raise TypeError('{0} is not JSON serializable'.format(obj))
209326
public static void print(final Object obj)
	{
		System.out.println(getInstance(obj.getClass()).serialise(obj));
	}
1100142
function styledJSON (obj) {
  let json = JSON.stringify(obj, null, 2)
  if (cli.color.enabled) {
    let cardinal = require('cardinal')
    let theme = require('cardinal/themes/jq')
    cli.log(cardinal.highlight(json, {json: true, theme: theme}))
  } else {
    cli.log(json)
  }
}
609843
def custom_print(data_structure, indent):
    
    for key, value in data_structure.items():
        print("\n%s%s:" % (' ' * attribute_indent * indent, str(key)), end=' ')
        if isinstance(value, OrderedDict):
            custom_print(value, indent + 1)
        elif isinstance(value, dict):
            custom_print(value, indent + 1)
        else:
            print("%s" % (str(value)), end=' ')
1084362
def to_json(obj):
    
    try:
        return json.dumps(obj, default=lambda obj: {k.lower(): v for k, v in obj.__dict__.items()},
                          sort_keys=False, separators=(',', ':')).encode()
    except Exception as e:
        logger.info("to_json: ", e, obj)
1062859
def prettyprint(self):
        """"""
        return json.dumps(self.asJSON(), sort_keys=True, indent=4, separators=(',', ': '))
489024
def write_json(data, filename):
    

    def custom_default(obj):
        if obj is None or (hasattr(obj, 'isNull') and obj.isNull()):
            return ''
        raise TypeError

    with open(filename, 'w') as json_file:
        json.dump(data, json_file, indent=2, default=custom_default)
274725
def pprint(j, no_pretty):
    
    if not no_pretty:
        click.echo(
            json.dumps(j, cls=PotionJSONEncoder, sort_keys=True, indent=4, separators=(",", ": "))
        )
    else:
        click.echo(j)
653881
def json_output(f):
    

    @wraps(f)
    def json_output_decorator(*args, **kwargs):
        @inject(config=Config)
        def get_config(config):
            return config

        config = get_config()

        rv = f(*args, **kwargs)
        indent = None
        if config.get('DEBUG', False):
            logging.getLogger(__name__).debug("Formatting JSON nicely.")
            indent = 2
        rv = json.dumps(rv, cls=AppModelJSONEncoder, indent=indent)
        _set_json_response_content_type()
        return rv

    return json_output_decorator
467682
function formatObject(o) {
		var s = String(o);
		if(s === '[object Object]' && typeof JSON !== 'undefined') {
			s = tryStringify(o, s);
		}
		return s;
	}
554538
function(json, options) {
	var indent = options.asText == 'pretty' ? '\t' : null;
	if (options.javascript) {
		return util.js.stringify(json, indent);
	}
	else {
		return JSON.stringify(json, null, indent);
	}
}
1080098
def json_formatter(obj):
    
    if isinstance(obj, str):
        # Make a list of size 1
        return json.dumps([obj], indent=True)
    else:
        return json.dumps(obj, indent=True, sort_keys=True)
254712
def object_to_json(obj, indent=2):
    
    instance_json = json.dumps(obj, indent=indent, ensure_ascii=False, cls=DjangoJSONEncoder)
    return instance_json
678342
function pprintJSON(formJson, opts, indentLevel, priorNodeStr) {
  opts = opts || {};
  opts.spaces = opts.spaces || 2;
  opts.lbracket = opts.lbracket || "[";
  opts.rbracket = opts.rbracket || "]";
  opts.separator = opts.separator || ", ";
  indentLevel = indentLevel || 0;
  var nl = opts.oneLine ? " " : "\n";
  var str = ""

  function indentToSpaces(indentLevel) {
    return(!opts.omitTop ? indentLevel * opts.spaces : (indentLevel - 1) * opts.spaces);
  }

  if(Array.isArray(formJson)) {
    var numSpaces = indentToSpaces(indentLevel);
    if(!(opts.omitTop && indentLevel === 0)) {
      // I added these last two checks below specifically for formatting html tags
      // (the length check might adversely effect formatting normal code not sure yet )
      if((priorNodeStr !== '"function"' && priorNodeStr !== 'function') &&
          formJson.length > 0 && formJson[0] !== "attr") {
        str += (priorNodeStr ? nl : "") // omit the unecessary *first* "\n"
        str += (priorNodeStr && numSpaces > 0 ? " ".repeat(numSpaces) : "")
      }
      str += opts.lbracket
    }

    if(formJson[0] === "object" || formJson[0] === "attr") {
      if(opts.attrsAsJson || opts.objectsAsJson) {
        // pretty print the key/value pairs of an object/attr as a js object:
        str += "{";
        for(var i=1; i<formJson.length;i+=2) {
          if(i === 1) { str += nl; }
          var propNameStr = pprintJSON(formJson[i], opts);
          propNameStr = ((propNameStr.indexOf("-") !== -1) ? '"' + propNameStr + '"' : propNameStr);
          str += (numSpaces+1 > 0 ? " ".repeat(indentToSpaces(indentLevel+1)) : "") +
                  propNameStr + ": " +
                  pprintJSON(formJson[i+1], opts, indentLevel + 2, formJson[i]) + (i+2 < formJson.length ? opts.separator : "") + nl;
        }
        str += "}";
      }
      else {
        // pretty print the key/value pairs of an object/attr as an s-expr list
        str += pprintJSON(formJson[0], opts) + opts.separator + nl;
        for(var i=1; i<formJson.length;i+=2) {
          str += (numSpaces+1 > 0 ? " ".repeat(indentToSpaces(indentLevel+1)) : "") +
                 pprintJSON(formJson[i], opts) + opts.separator +
                 pprintJSON(formJson[i+1], opts, indentLevel + 2, formJson[i]) + (i+2 < formJson.length ? opts.separator : "") + nl;
        }
      }
    }
    else {
      // pretty print the body of a normal list
      var priorNodeStr;
      formJson.forEach(function(node, i) {
        priorNodeStr = pprintJSON(node, opts, indentLevel + 1, priorNodeStr)
        str += priorNodeStr
        if(i < formJson.length - 1) {
          str += opts.separator
        }
      })
    }
    if(!(opts.omitTop && indentLevel === 0)) {
      str += opts.rbracket
    }
  }
  else if(formJson == null) {
    str += "null";
  }
  else if(typeof formJson === 'string' && !opts.bareSymbols) {
    // I had backslashed single quotes below -
    // but jsonlint rejected so I don't...
    str += ('"' + formJson.replace(/[\\"]/g, '\\$&') + '"')
  }
  else if(formJson.toString) {
    str += formJson.toString();
  }
  else {
    throw new Error('Unknown form type in pprintJSON: ' + formJson + ' (' + typeof formJson + ')');
  }
  return str
}
28854
def json_default(obj):
    
    if isinstance(obj, datetime):
        return obj.strftime("%Y-%m-%d %H:%M:%S")
    elif isinstance(obj, Decimal):
        return float(obj)
    elif isinstance(obj, uuid.UUID):
        return text_type(obj)
    else:
        try:
            return text_type(obj)
        except:
            pass

    raise TypeError("%r is not JSON serializable" % obj)