JavaScript Python PHP
function executar(input = '{"nome":"Bennu","ativo":true}', compact = false, indent = 2) {
function validateJson(input) {
if (!input.trim())
throw new Error('Informe um documento JSON.');
if (input.length > 1000000)
throw new Error('Limite: 1 milhão de caracteres.');
try {
// Syntax only. Never use these parsed numbers to produce the formatted output.
JSON.parse(input);
}
catch (cause) {
const message = cause instanceof Error ? cause.message : 'Erro de sintaxe';
const offset = message.match(/position (\d+)/i);
const nativeLocation = message.match(/line (\d+) column (\d+)/i);
const position = offset ? Math.min(Number(offset[1]), input.length) : /end of JSON/i.test(message) ? input.length : undefined;
const before = position === undefined ? undefined : input.slice(0, position);
const line = before === undefined ? nativeLocation?.[1] : String(before.split('\n').length);
const column = before === undefined ? nativeLocation?.[2] : String(before.length - before.lastIndexOf('\n'));
const location = line && column ? ` (linha ${line}, coluna ${column})` : '';
throw new Error(`JSON inválido${location}: ${message}`);
}
const first = input.trim()[0];
const type = first === '{' ? 'objeto' : first === '[' ? 'lista' : first === '"' ? 'string' : first === 'n' ? 'null' : first === 't' || first === 'f' ? 'booleano' : 'número';
return { valid: true, type };
}
function formatJson(input, compact = false, indent = 2) {
validateJson(input);
if (typeof compact !== 'boolean' || !Number.isInteger(indent) || indent < 1 || indent > 8)
throw new Error('Indentação: de 1 a 8 espaços; compactar deve ser booleano.');
const text = input.trim();
const parts = [];
let depth = 0, quoted = false, escaped = false, length = 0;
const append = (value) => {
length += value.length;
if (length > 5000000)
throw new Error('O resultado excede o limite de 5 milhões de caracteres.');
parts.push(value);
};
const newline = () => {
if (!compact)
append('\n' + ' '.repeat(depth * indent));
};
const next = (index) => {
while (index < text.length && /[\t\n\r ]/.test(text[index]))
index++;
return text[index];
};
for (let i = 0; i < text.length; i++) {
const ch = text[i];
if (quoted) {
append(ch);
if (escaped)
escaped = false;
else if (ch === '\\')
escaped = true;
else if (ch === '"')
quoted = false;
continue;
}
if (/[\t\n\r ]/.test(ch))
continue;
if (ch === '"') {
quoted = true;
append(ch);
continue;
}
if (ch === '{' || ch === '[') {
append(ch);
if (++depth > 100)
throw new Error('Limite: 100 níveis de aninhamento.');
if (next(i + 1) !== (ch === '{' ? '}' : ']'))
newline();
}
else if (ch === '}' || ch === ']') {
depth--;
if (parts[parts.length - 1] !== '{' && parts[parts.length - 1] !== '[')
newline();
append(ch);
}
else if (ch === ',') {
append(ch);
newline();
}
else if (ch === ':')
append(compact ? ':' : ': ');
else
append(ch);
}
return parts.join('');
}
return formatJson(input, compact, indent);
}
import json
def executar(input='{"nome":"Bennu","ativo":true}', compact=False, indent=2):
if type(compact) is not bool or type(indent) is not int or not 1 <= indent <= 8: raise ValueError('Formatação inválida')
if not input.strip() or len(input) > 1000000: raise ValueError('Entrada vazia ou limite excedido')
def reject(value): raise ValueError('Constante JSON inválida: ' + value)
json.loads(input, parse_int=str, parse_float=str, parse_constant=reject)
text = input.strip()
parts, depth, quoted, escaped = [], 0, False, False
def newline():
if not compact: parts.append('\n' + ' ' * (depth * indent))
for i, ch in enumerate(text):
if quoted:
parts.append(ch)
if escaped: escaped = False
elif ch == '\\': escaped = True
elif ch == '"': quoted = False
continue
if ch in ' \t\r\n': continue
if ch == '"': quoted = True; parts.append(ch)
elif ch in '{[':
parts.append(ch); depth += 1
if depth > 100: raise ValueError('Limite de aninhamento excedido')
if not text[i+1:].lstrip(' \t\r\n').startswith('}' if ch == '{' else ']'): newline()
elif ch in '}]':
depth -= 1
if parts[-1] not in ('{','['): newline()
parts.append(ch)
elif ch == ',': parts.append(ch); newline()
elif ch == ':': parts.append(':' if compact else ': ')
else: parts.append(ch)
output = ''.join(parts)
if len(output) > 5000000: raise ValueError('Limite de saída excedido')
return output
<?php
function executar($input = '{"nome":"Bennu","ativo":true}', $compact = false, $indent = 2) {
if (!is_bool($compact) || !is_int($indent) || $indent < 1 || $indent > 8) throw new InvalidArgumentException('Formatação inválida');
if (trim($input) === '' || strlen($input) > 1000000) throw new InvalidArgumentException('Entrada vazia ou limite excedido');
json_decode($input, false, 512, JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING);
$text = trim($input); $parts = []; $depth = 0; $quoted = false; $escaped = false;
$newline = function () use (&$parts, &$depth, $compact, $indent) { if (!$compact) $parts[] = "\n" . str_repeat(' ', $depth * $indent); };
for ($i = 0; $i < strlen($text); $i++) {
$ch = $text[$i];
if ($quoted) {
$parts[] = $ch;
if ($escaped) $escaped = false;
elseif ($ch === '\\') $escaped = true;
elseif ($ch === '"') $quoted = false;
continue;
}
if (str_contains(" \t\r\n", $ch)) continue;
if ($ch === '"') { $quoted = true; $parts[] = $ch; }
elseif ($ch === '{' || $ch === '[') {
$parts[] = $ch; $depth++;
if ($depth > 100) throw new InvalidArgumentException('Limite de aninhamento excedido');
$next = ltrim(substr($text, $i + 1), " \t\r\n");
if ($next[0] !== ($ch === '{' ? '}' : ']')) $newline();
} elseif ($ch === '}' || $ch === ']') {
$depth--; if (end($parts) !== '{' && end($parts) !== '[') $newline(); $parts[] = $ch;
} elseif ($ch === ',') { $parts[] = $ch; $newline(); }
elseif ($ch === ':') $parts[] = $compact ? ':' : ': ';
else $parts[] = $ch;
}
$output = implode('', $parts);
if (strlen($output) > 5000000) throw new InvalidArgumentException('Limite de saída excedido');
return $output;
}