beautifier

@param string		$json
@param string		$tab
@param strgin		$break
@return string
488994
public static function beautify( $json, $tab = "\t", $break = "\n" ) {
		
		$buffer = "";
		$level = 0;
		
		$in_string = false; 
		
		$len = strlen( $json ); 
		
		for($c = 0; $c < $len; $c++) { 
			
			$char = $json[$c]; 
			
			switch( $char ) { 
				case '{': 
				case '[': 
					if( !$in_string ) { 
						$buffer .= $char . "\n" . str_repeat($tab, $level+1); $level++; 
					} else { 
						$buffer .= $char; 
					} 
				break; 
				case '}': 
				case ']': 
					if( !$in_string ) { 
						$level--; $buffer .= "\n" . str_repeat($tab, $level) . $char; 
					} else { 
						$buffer .= $char; 
					} 
				break; 
				case ',': 
					if( !$in_string ) { 
						$buffer .= ",\n" . str_repeat($tab, $level); 
					} else { 
						$buffer .= $char; 
					} 
				break; 
				case ':': 
					if( !$in_string ) { 
						$buffer .= ": "; 
					} else { 
						$buffer .= $char; 
					} 
				break; 
				case '"': 
					if( $c > 0 && $json[$c-1] != '\\' ) { 
						$in_string = !$in_string; 
					} 
				default: 
					$buffer .= $char; 
				break;                    
			}
		}
		return $buffer;
	}
132349
protected function _element($data, $tab, $start)
    {
        static $start;

        $eof     = EOL;
        $output  = '';
        $attrs   = '';
        $tab     = str_repeat("\t", $start);

        if( ! is_array($data) )
        {
            return $data.$eof;
        }
        else
        {
            foreach( $data as $k => $v )
            {
                if( IS::realNumeric($k) )
                {
                    $value = $k;
                    $k     = 'li';
                }
                else
                {
                    $value = NULL;
                }

                $end = Base::prefix(Arrays\GetElement::first(explode(' ', $k)));

                if( ! is_array($v) )
                {

                    $output .= "$tab<$k>$v<$end>$eof";
                }
                else
                {
                    if( stripos($k, 'ul') !== 0 && stripos($k, 'ol') !== 0 && $k !== 'li' )
                    {
                        $value = $k;
                        $k     = 'li';
                        $end   = Base::prefix($k);
                    }
                    else
                    {
                        $value = NULL;
                    }

                    $output .= $tab."<$k>$value$eof".$this->_element($v, $tab, $start++).$tab."<$end>".$tab.$eof;
                    $start--;
                }
            }
        }

        return $output;
    }
577827
async function generateJson(options, generatorResult) {
  const jsonPath = (
    options.jsonPath ||
    `${ path.join(options.outputDir, '/' + options.fontName) }.json`
  )

  const css = generatorResult.generateCss()
  let map = {}

  css.replace(CSS_PARSE_REGEX, (match, name, code) => map[name] = code)

  await fsAsync.writeFile(jsonPath, JSON.stringify(map, null, 4))
}
827872
public static function json($input = false, $exit = true) {

        if ($input) {

            echo Format::toJson($input);
            if ($exit) {

                exit();
            }
        }

        return false;
    }
288522
private function simple_json_parser($json){
        $json = str_replace("{","",str_replace("}","", $json));
        $jsonValue = explode(",", $json);
        $arr = array();
        foreach($jsonValue as $v){
            $jValue = explode(":", $v);
            $arr[str_replace('"',"", $jValue[0])] = (str_replace('"', "", $jValue[1]));
        }
        return $arr;
    }
503939
function(type, filter, tabs) {
			if (isType(type)) {
				return JSON.stringify(parse(type), filter, tabs);
			} else {
				throw new TypeError("Expected edb.Object|edb.Array");
			}
		}
1333185
public static function toJson($input = false, $pretty = false) {

        if ($input) {

            switch (Data::type($input)) {
                case 'array':
                    $json = self::arrayToJson($input, $pretty);
                    break;
                case 'object':
                    $json = self::objectToJson($input, $pretty);
                    break;
                default:
                    $json = false;
                    break;
            }

            if (Validate::isJson($json)) {

                return $json;
            }
        }

        return false;
    }
1094840
public static function prettyJSONPrint($json)
    {
        $result = '';
        $level = 0;
        $in_quotes = false;
        $in_escape = false;
        $ends_line_level = null;
        $json_length = strlen($json);

        for ($i = 0; $i < $json_length; $i++) {
            $char = $json[$i];
            $new_line_level = null;
            $post = "";
            if ($ends_line_level !== null) {
                $new_line_level = $ends_line_level;
                $ends_line_level = null;
            }
            if ($in_escape) {
                $in_escape = false;
            } else {
                if ($char === '"') {
                    $in_quotes = !$in_quotes;
                } else {
                    if (!$in_quotes) {
                        switch ($char) {
                            case '}':
                            case ']':
                                $level--;
                                $ends_line_level = null;
                                $new_line_level = $level;
                                break;

                            case '{':
                            case '[':
                                $level++;
                            case ',':
                                $ends_line_level = $level;
                                break;

                            case ':':
                                $post = " ";
                                break;

                            case " ":
                            case "\t":
                            case "\n":
                            case "\r":
                                $char = "";
                                $ends_line_level = $new_line_level;
                                $new_line_level = null;
                                break;
                        }
                    } else {
                        if ($char === '\\') {
                            $in_escape = true;
                        }
                    }
                }
            }
            if ($new_line_level !== null) {
                $result .= "\n" . str_repeat("\t", $new_line_level);
            }
            $result .= $char . $post;
        }

        return $result;
    }
1108481
public static function indent(string $strJSON) : string
    {
        $strReturn = "";
        $indentLevel = 0;

        $insideQuotes = false;
        $insideEscape = false;

        $endLineLevel = null;

        $utf8split = preg_split('//u', $strJSON, -1, PREG_SPLIT_NO_EMPTY);
        for ($i = 0; $i < count($utf8split); $i++) {
            $c = $utf8split[$i];
            $newLineLevel = null;
            $post = "";

            if ($endLineLevel !== null) {
                $newLineLevel = $endLineLevel;
                $endLineLevel = null;
            }


            if ($insideEscape === true) {
                $insideEscape = false;
            } elseif ($c === '"') {
                $insideQuotes = !$insideQuotes;
            } elseif ($insideQuotes === false) {
                switch ($c) {
                    case "}":
                    case "]":
                        $indentLevel--;
                        $endLineLevel = null;
                        $newLineLevel = $indentLevel;
                        break;

                    case "{":
                    case "[":
                        $indentLevel++;
                    case ",":
                        $endLineLevel = $indentLevel;
                        break;

                    case ":":
                        $post = " ";
                        break;

                    case " ":
                    case "\t":
                    case "\n":
                    case "\r":
                        $c = "";
                        $endLineLevel = $newLineLevel;
                        $newLineLevel = null;
                        break;
                }
            } elseif ($c === "\\") {
                $insideEscape = true;
            }


            if ($newLineLevel !== null) {
                $strReturn .= "\n" . str_repeat("\t", $newLineLevel);
            }

            $strReturn .= $c . $post;
        }

        return $strReturn;
    }
6260
public static function prettyPrint($json, $options = array())
    {
        $tokens = preg_split('|([\{\}\]\[,])|', $json, -1, PREG_SPLIT_DELIM_CAPTURE);
        $result = "";
        $indent = 0;

        $ind = "    ";
        if (isset($options['indent'])) {
            $ind = $options['indent'];
        }

        $inLiteral = false;
        foreach ($tokens as $token) {
            $token = trim($token);
            if ($token == "") {
                continue;
            }

            if (preg_match('/^("(?:.*)"):[ ]?(.*)$/', $token, $matches)) {
                $token = $matches[1] . ': ' . $matches[2];
            }

            $prefix = str_repeat($ind, $indent);
            if (!$inLiteral && ($token == "{" || $token == "[")) {
                $indent++;
                if ($result != "" && $result[strlen($result)-1] == "\n") {
                    $result .= $prefix;
                }
                $result .= "$token\n";
            } elseif (!$inLiteral && ($token == "}" || $token == "]")) {
                $indent--;
                $prefix = str_repeat($ind, $indent);
                $result .= "\n$prefix$token";
            } elseif (!$inLiteral && $token == ",") {
                $result .= "$token\n";
            } else {
                $result .= ($inLiteral ?  '' : $prefix) . $token;

                //remove escaped backslash sequences causing false positives in next check
                $token = str_replace('\\', '', $token);
                // Count # of unescaped double-quotes in token, subtract # of
                // escaped double-quotes and if the result is odd then we are
                // inside a string literal
                if ((substr_count($token, '"')-substr_count($token, '\\"')) % 2 != 0) {
                    $inLiteral = !$inLiteral;
                }
            }
        }
        return $result;
    }
445602
function parse_style_json_object(text, options)
{
	// remove multiline comments
	text = text.replace(/\/\*([\s\S]*?)\*\//g, '')

	// ignore curly braces for now.
	// maybe support curly braces along with tabulation in future
	text = text.replace(/[\{\}]/g, '')

	const lines = text.split('\n')

	// helper class for dealing with tabulation
	const tabulator = new Tabulator(Tabulator.determine_tabulation(lines))

	// parse text into JSON object
	let style_json = parse_style_class(tabulator.extract_tabulation(lines), [])

	// expand CSS shorthand properties
	// (e.g. `margin: 1px` -> `margin-left: 1px; ...`)
	if (options.expand)
	{
		style_json = style_builder.build(style_json)
	}

	// expand "modifier" style classes
	// (which can override some of the expanded shorthand CSS properties)
	return expand_modifier_style_classes(style_json)
}
402817
private function composeJsonValidationOnCreateRules(
        SettingsProviderInterface $settingsProvider,
        FileSystemInterface $fileSystem,
        string $singular
    ): TemplateOutput {
        $folder = $settingsProvider
                      ->get(FluteSettingsInterface::class)[FluteSettingsInterface::KEY_JSON_VALIDATORS_FOLDER];

        $outputRootFolder = $this->filterOutFolderMask($folder);
        $outputFileName   = $singular . 'CreateJson.php';
        $outputContent    = $this->composeTemplateContent(
            $fileSystem,
            $this->getTemplatePath('JsonRulesOnCreate.txt'),
            [
                '{%SINGULAR_CC%}' => $singular,
                '{%SINGULAR_LC%}' => strtolower($singular),
            ]
        );

        return new TemplateOutput($outputRootFolder, $outputFileName, $outputContent, $singular);
    }
1207141
public function outputPHP($v, $tabs=0, $line=false) {
		$r = '';

		if($line)
			$r .= "\n".str_repeat("\t", $tabs);

		if(is_array($v)) {
			$r .= '[';
			if($v === array_values($v)) {
				foreach($v as $_v)
					$r .= $this->outputPHP($_v, $tabs+1, true).",";
			}
			else {
				foreach($v as $_k=>$_v)
					$r .= $this->outputPHP($_k, $tabs+1, true).' => '.$this->outputPHP($_v, $tabs+1).",";
			}
			$r .= "\n".str_repeat("\t", $tabs).']';

			return $r;
		}
		else
			return $r.var_export($v, true);
	}
1195629
protected static function prettyPrint($json)
    {
        $result = '';
        $pos = 0;
        $indentation = '    ';
        $newline = "\n";
        $previousChar = '';
        $outOfQuotes = true;

        // Unescape slashes.
        if (strpos($json, '/')) {
            $json = preg_replace('#\134{1}/#', '/', $json);
        }

        $stringLength = strlen($json);

        for ($i = 0; $i <= $stringLength; $i++) {

            // Grab the next character in the string.
            $char = substr($json, $i, 1);

            if (':' == $previousChar && $outOfQuotes) {
                $result .= ' ';
            }

            // Are we inside a quoted string?
            if ('"' == $char && $previousChar != '\\') {
                $outOfQuotes = !$outOfQuotes;

                // If this character is the end of an element,
                // output a new line and indent the next line.
            } elseif (('}' == $char || ']' == $char) && $outOfQuotes) {
                $result .= $newline;
                $pos --;
                for ($j = 0; $j < $pos; $j++) {
                    $result .= $indentation;
                }
            }

            // Add the character to the result string.
            $result .= $char;

            // If the last character was the beginning of an element,
            // output a new line and indent the next line.
            if ((',' == $char || '{' == $char || '[' == $char) && $outOfQuotes) {
                $result .= $newline;
                if ('{' == $char || '[' == $char) {
                    $pos ++;
                }

                for ($j = 0; $j < $pos; $j++) {
                    $result .= $indentation;
                }
            }

            $previousChar = $char;
        }

        return $result;
    }
599865
def prettify_json_file(file_list):
    
    for json_file in set(file_list):
        if not json_file.endswith(".json"):
            logger.log_warning("Only JSON file format can be prettified, skip: {}".format(json_file))
            continue

        logger.color_print("Start to prettify JSON file: {}".format(json_file), "GREEN")

        dir_path = os.path.dirname(json_file)
        file_name, file_suffix = os.path.splitext(os.path.basename(json_file))
        outfile = os.path.join(dir_path, "{}.pretty.json".format(file_name))

        with io.open(json_file, 'r', encoding='utf-8') as stream:
            try:
                obj = json.load(stream)
            except ValueError as e:
                raise SystemExit(e)

        with io.open(outfile, 'w', encoding='utf-8') as out:
            json.dump(obj, out, indent=4, separators=(',', ': '))
            out.write('\n')

        print("success: {}".format(outfile))
80759
def format_json(json_object, indent):
    
    indent_str = "\n" + " " * indent
    json_str = json.dumps(json_object, indent=2, default=serialize_json_var)
    return indent_str.join(json_str.split("\n"))
319957
function processJson (json) {
                        if (json.length != 1) {
                            renderContext.renderErrors[graph.id] = "TSDB results doesn't contain exactly 1 metric, was "+json.length;
                            renderContext.renderMessages[graph.id] = "";
                            return;
                        }

                        var series = json[0];

                        if (heatmapOptions.excludeNegative) {
                            for (var i=0; i<series.dps.length; i++) {
                                if (series.dps[i][1] < 0) {
                                    series.dps[i][1] = 0;
                                }
                            }
                        }

                        var isFilteredOutFn = function(value) {
                            return false;
                        }
                        var tsdbLinkRangeLower = "";
                        var tsdbLinkRangeUpper = "";
                        if ((heatmapOptions.filterLowerBound != null && heatmapOptions.filterLowerBound != "") || (heatmapOptions.filterUpperBound != null && heatmapOptions.filterUpperBound != "")) {
                            if (heatmapOptions.filterUpperBound == null || heatmapOptions.filterUpperBound == "") {
                                try {
                                    var lower = parseInt(heatmapOptions.filterLowerBound);
                                    tsdbLinkRangeLower = lower;
                                    isFilteredOutFn = function(value) {
                                        return value < lower
                                    };
                                }
                                catch (e) {
                                    // ignore
                                }
                            }
                            else if (heatmapOptions.filterLowerBound == null || heatmapOptions.filterLowerBound == "") {
                                try {
                                    var upper = parseInt(heatmapOptions.filterUpperBound);
                                    tsdbLinkRangeUpper = upper;
                                    isFilteredOutFn = function(value) {
                                        return value > upper
                                    };
                                }
                                catch (e) {
                                    // ignore
                                }
                            }
                            else {
                                try {
                                    var lower = parseInt(heatmapOptions.filterLowerBound);
                                    var upper = parseInt(heatmapOptions.filterUpperBound);
                                    tsdbLinkRangeLower = lower;
                                    tsdbLinkRangeUpper = upper;
                                    isFilteredOutFn = function(value) {
                                        return value < lower || value > upper
                                    };
                                }
                                catch (e) {
                                    // ignore
                                }
                            }
                        }

                        // remove old heatmaps..
                        d3.select(divSelector)
                            .selectAll("svg")
                            .remove();

                        var heatmap = renderer.heatmap()
                            .cellSize(cellSize)
                            .scale(d3.scale.quantize())
                            .dps(series.dps)
                            .width(width)
                            .height(height)
                            .colourScheme(heatmapOptions.colourScheme);

                        if (style == "week_day") {
                            heatmap.weekDayRender(divSelector, fromYear, toYear, isFilteredOutFn);
                        }
                        else if (style == "day_hour") {
                            heatmap.dayHourRender(divSelector, fromMonth, toMonth, isFilteredOutFn);
                        }

                        if (heatmapOptions.excludeNegative && true && (tsdbLinkRangeLower == "" || tsdbLinkRangeLower < 0)) {
                            tsdbLinkRangeLower = 0;
                        }
                        var yAxisParams = {
                            range: "[" + tsdbLinkRangeLower + ":" + tsdbLinkRangeUpper + "]"
                        };
                        ret.tsdb_export_link = graphServices.tsdbGraphUrl("/#", renderContext, config, global, graph, queries, "x1y1", downsampleOverrideFn, yAxisParams, /*y2AxisParams*/null, /*keyParams*/{}, /*lineSmoothing*/false, /*style*/null, /*globalAnnotations*/false);
                        renderContext.renderMessages[graph.id] = "";
                        renderContext.graphRendered(graph.id);
                        return;
                    }