Чтобы отформатировать JSON онлайн с помощью PHP, вы можете использовать следующие методы и примеры кода:
-
Использование функций
json_encode()
иjson_decode()
:$json = '{"name":"John","age":30,"city":"New York"}'; // Format JSON $formattedJson = json_encode(json_decode($json), JSON_PRETTY_PRINT); // Output formatted JSON echo $formattedJson;
-
Использование
json_encode()
с флагомJSON_PRETTY_PRINT
:$json = '{"name":"John","age":30,"city":"New York"}'; // Decode JSON to an associative array $data = json_decode($json, true); // Format JSON $formattedJson = json_encode($data, JSON_PRETTY_PRINT); // Output formatted JSON echo $formattedJson;
-
Использование класса
Zend\Json\Json
из Zend Framework:require_once 'Zend/Json/Json.php'; $json = '{"name":"John","age":30,"city":"New York"}'; // Format JSON $formattedJson = Zend\Json\Json::prettyPrint($json); // Output formatted JSON echo $formattedJson;
-
Использование класса
Symfony\Component\Serializer\Encoder\JsonEncoder
из компонента Symfony Serializer:use Symfony\Component\Serializer\Encoder\JsonEncoder; use Symfony\Component\Serializer\Serializer; $json = '{"name":"John","age":30,"city":"New York"}'; // Create a JSON encoder $encoder = new JsonEncoder(); // Create a serializer $serializer = new Serializer([], [$encoder]); // Format JSON $formattedJson = $serializer->encode(json_decode($json), 'json', ['json_encode_options' => JSON_PRETTY_PRINT]); // Output formatted JSON echo $formattedJson;
-
Использование класса
League\JsonGuard\Dumper
из библиотеки League\JsonGuard:use League\JsonGuard\Dumper; $json = '{"name":"John","age":30,"city":"New York"}'; // Create a JSON dumper $dumper = new Dumper(); // Format JSON $formattedJson = $dumper->dump(json_decode($json)); // Output formatted JSON echo $formattedJson;