<?php
/**
* Formats a JSON object for readability.
*
* @param mixed $data The data to format.
* @param int $indent The indentation level.
* @return string The formatted JSON string.
*/
function formatJson( $data, $indent = 0 ) {
$output = '';
if ( is_array( $data ) ) {
$output .= '{\n';
$indentation = str_repeat( ' ', $indent ); // Calculate indentation
foreach ( $data as $key => $value ) {
$output .= $indentation . '"' . json_encode( $key ) . ': ';
$output .= formatJson( $value, $indent + 1 ); // Recursive call
}
$output .= $indentation . ',\n';
$output .= $indentation . '}';
} elseif ( is_object( $data ) ) {
$output .= '{\n';
$indentation = str_repeat( ' ', $indent );
$keys = array_keys((array)$data); //Get keys from object
foreach ($keys as $key) {
$output .= $indentation . '"' . json_encode($key) . ': ';
$output .= formatJson((array)$data->$key, $indent + 1);
}
$output .= $indentation . ',\n';
$output .= $indentation . '}';
} else {
$output .= '"' . json_encode( $data ) . '"\n'; // Simple value
}
return $output;
}
//Example usage:
if(isset($argv)){
$json_string = $argv[1]; // Get JSON string from command line argument
$formatted_json = formatJson(json_decode($json_string, true), 0); //Decode and format
echo $formatted_json;
}
?>
Add your comment