1. <?php
  2. /**
  3. * Formats a JSON object for readability.
  4. *
  5. * @param mixed $data The data to format.
  6. * @param int $indent The indentation level.
  7. * @return string The formatted JSON string.
  8. */
  9. function formatJson( $data, $indent = 0 ) {
  10. $output = '';
  11. if ( is_array( $data ) ) {
  12. $output .= '{\n';
  13. $indentation = str_repeat( ' ', $indent ); // Calculate indentation
  14. foreach ( $data as $key => $value ) {
  15. $output .= $indentation . '"' . json_encode( $key ) . ': ';
  16. $output .= formatJson( $value, $indent + 1 ); // Recursive call
  17. }
  18. $output .= $indentation . ',\n';
  19. $output .= $indentation . '}';
  20. } elseif ( is_object( $data ) ) {
  21. $output .= '{\n';
  22. $indentation = str_repeat( ' ', $indent );
  23. $keys = array_keys((array)$data); //Get keys from object
  24. foreach ($keys as $key) {
  25. $output .= $indentation . '"' . json_encode($key) . ': ';
  26. $output .= formatJson((array)$data->$key, $indent + 1);
  27. }
  28. $output .= $indentation . ',\n';
  29. $output .= $indentation . '}';
  30. } else {
  31. $output .= '"' . json_encode( $data ) . '"\n'; // Simple value
  32. }
  33. return $output;
  34. }
  35. //Example usage:
  36. if(isset($argv)){
  37. $json_string = $argv[1]; // Get JSON string from command line argument
  38. $formatted_json = formatJson(json_decode($json_string, true), 0); //Decode and format
  39. echo $formatted_json;
  40. }
  41. ?>

Add your comment