Darmowy Formater i Walidator JSON Online

Formatuj i waliduj dane JSON. Upiększ lub zminimalizuj ciągi JSON.

0 znaków

Czym jest formater JSON?

Formater JSON to narzędzie, które przekształca nieuporządkowane, niesformatowane dane JSON w czysty, czytelny format z odpowiednim wcięciem i łamaniem linii. Sprawdza również, czy Twój JSON jest poprawny składniowo.

Essential Uses of JSON Formatting

  • Debugging API Responses: When calling REST APIs, responses are often minified (no whitespace, single line). Formatting these responses makes them readable for debugging. For example, a minified API response {"user":{"id":123,"name":"John","roles":["admin","editor"]}} is hard to parse visually. Formatted with indentation, the structure becomes clear. You can see the nested user object, the id and name fields, and the roles array. Essential for verifying API behavior, inspecting nested data, and debugging integration issues.
  • seo.json_formatter.use_debug seo.json_formatter.use_debug_desc
  • Analyzing Log Files and Error Messages: Application logs, error messages, and monitoring systems often output JSON. These JSON blobs are typically minified and difficult to read. Formatting log JSON helps you understand error context, trace nested data structures in logs, and analyze application behavior. For example, formatting a structured log entry reveals the timestamp, log level, message, and contextual data clearly.
  • Editing Configuration Files: Modern applications use JSON for config files: package.json (Node.js), composer.json (PHP), tsconfig.json (TypeScript), launch.json (VS Code), etc. When these files are minified or poorly formatted, editing them becomes error-prone. Formatting ensures proper indentation, making it easy to spot syntax errors (missing commas, unclosed brackets) and understand configuration structure. Always format before editing, and validate after.

Jak działa formatowanie JSON?

Formatowanie JSON (zwane także pretty-printing lub beautifying) dodaje białe znaki, wcięcia i łamanie wierszy do zminimalizowanego JSON bez zmiany danych. Operacja odwrotna (minifikacja) usuwa wszystkie niepotrzebne białe znaki. Oto proces techniczny:

  • Krok 1 - Parsowanie JSON: Ciąg wejściowy jest parsowany do struktury danych w pamięci (obiekty, tablice, ciągi, liczby, wartości logiczne, null). Jeśli parsowanie się nie powiedzie, zgłaszany jest błąd składniowy z pozycją problemu.
  • Krok 2 - Przejście przez strukturę: Formater przechodzi przez parsowaną strukturę rekurencyjnie, odwiedzając każdy obiekt, tablicę i wartość po kolei.
  • Krok 3 - Zastosowanie wcięć: Dla każdego poziomu zagnieżdżenia, formater dodaje wcięcie (zazwyczaj 2 lub 4 spacje). Otwierające nawiasy klamrowe i kwadratowe rozpoczynają nowe wcięte bloki; zamykające wracają do poprzedniego poziomu.
  • Krok 4 - Serializacja z powrotem do ciągu: Sformatowana struktura jest konwertowana z powrotem do ciągu JSON z odpowiednimi białymi znakami, łamaniem wierszy po każdej wartości i przecinkami między elementami.

Przykład: Zminimalizowany JSON {"name":"John","age":30,"roles":["admin","editor"]} jest formatowany do struktury wieloliniowej z każdą parą klucz-wartość w osobnym wierszu, odpowiednim wcięciem dla zagnieżdżonej tablicy i wyraźną hierarchią wizualną.

JSON: The Universal Data Format

JSON (JavaScript Object Notation) został określony przez Douglasa Crockforda i ustandaryzowany w RFC 8259 (2017). JSON jest lekkim, niezależnym od języka formatem danych opartym na składni obiektów JavaScript. Stał się dominującym formatem dla internetowych API, plików konfiguracyjnych i wymiany danych, w dużej mierze zastępując XML w wielu aplikacjach.

JSON Security Considerations

JSON formatting does not validate data safety. Always validate and sanitize JSON content from untrusted sources before using it in your application. Learn about encoding security

Formatowanie JSON w językach programowania

Każdy język programowania może formatować (upiększać) i minimalizować JSON. Oto przykłady:

// Beautify (pretty print)
$formatted = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
// Result: formatted with 4-space indent

// Minify (compact)
$minified = json_encode($data);
// Result: no whitespace

// With custom options
$json = json_encode($data,
    JSON_PRETTY_PRINT |
    JSON_UNESCAPED_UNICODE |
    JSON_UNESCAPED_SLASHES
);

// Parsing (with error handling)
$data = json_decode($jsonString, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    echo "JSON Error: " . json_last_error_msg();
}
// Beautify with 2-space indent
const formatted = JSON.stringify(data, null, 2);

// Beautify with 4-space indent
const formatted = JSON.stringify(data, null, 4);

// Minify (compact)
const minified = JSON.stringify(data);

// Parse with error handling
try {
    const data = JSON.parse(jsonString);
} catch (error) {
    console.error("JSON parse error:", error.message);
}

// Replacer function (custom serialization)
const json = JSON.stringify(data, (key, value) => {
    // Exclude private fields
    if (key.startsWith('_')) return undefined;
    return value;
}, 2);
import json

# Beautify with 2-space indent
formatted = json.dumps(data, indent=2)

# Beautify with sorted keys
formatted = json.dumps(data, indent=2, sort_keys=True)

# Minify (compact)
minified = json.dumps(data, separators=(',', ':'))
# separators removes spaces after commas and colons

# Parse with error handling
try:
    data = json.loads(json_string)
except json.JSONDecodeError as e:
    print(f"JSON error: {e.msg} at line {e.lineno}")

# Pretty print to console
print(json.dumps(data, indent=2))
import (
    "encoding/json"
    "fmt"
)

// Beautify with indent
formatted, err := json.MarshalIndent(data, "", "  ")
if err != nil {
    fmt.Println("JSON marshal error:", err)
}

// Minify (compact)
minified, err := json.Marshal(data)

// Parse with error handling
var data MyStruct
err := json.Unmarshal([]byte(jsonString), &data)
if err != nil {
    fmt.Println("JSON unmarshal error:", err)
}

// Custom indentation
formatted, _ := json.MarshalIndent(data, ">", "----")
// Prefix: >, indent: ----
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;

// Beautify
Gson gson = new GsonBuilder()
    .setPrettyPrinting()
    .create();
String formatted = gson.toJson(data);

// Minify
Gson gson = new Gson();
String minified = gson.toJson(data);

// Parse with error handling
try {
    MyObject obj = gson.fromJson(jsonString, MyObject.class);
} catch (JsonSyntaxException e) {
    System.err.println("JSON error: " + e.getMessage());
}
require 'json'

# Beautify
formatted = JSON.pretty_generate(data)
# Default: 2-space indent

# Beautify with custom indent
formatted = JSON.pretty_generate(data, indent: '    ')
# 4-space indent

# Minify
minified = JSON.generate(data)

# Parse with error handling
begin
  data = JSON.parse(json_string)
rescue JSON::ParserError => e
  puts "JSON error: #{e.message}"
end
using Newtonsoft.Json;

// Beautify (pretty print)
string formatted = JsonConvert.SerializeObject(data,
    Formatting.Indented);

// Minify (compact)
string minified = JsonConvert.SerializeObject(data,
    Formatting.None);

// Parse with error handling
try
{
    var obj = JsonConvert.DeserializeObject<MyObject>(jsonString);
}
catch (JsonException ex)
{
    Console.WriteLine($"JSON error: {ex.Message}");
}

Related Tools

Working with JWT tokens? Our JWT Decoder decodes and formats the JSON header and payload from JWT tokens.

Have Base64-encoded JSON? First use our Base64 Decoder to decode, then format the resulting JSON.

Passing JSON in URL parameters? Encode it with our URL Encoder after minifying for compact URLs.