1. <?php
  2. /**
  3. * Parses JSON API responses.
  4. *
  5. * This function takes a JSON string as input and returns an associative array
  6. * representing the parsed data. Handles basic error checking.
  7. *
  8. * @param string $json_string The JSON string to parse.
  9. * @return array|null An associative array representing the parsed JSON data,
  10. * or null if parsing fails.
  11. */
  12. function parseJson(string $json_string): ?array
  13. {
  14. // Remove whitespace for cleaner parsing
  15. $json_string = trim($json_string);
  16. // Check if the input is valid JSON
  17. if (empty($json_string)) {
  18. return null; // Return null for empty input
  19. }
  20. $data = json_decode($json_string, true);
  21. if (json_last_error() !== JSON_ERROR_NONE) {
  22. error_log("JSON decode error: " . json_last_error_msg()); // Log the error
  23. return null; // Return null if decoding fails
  24. }
  25. return $data;
  26. }
  27. /**
  28. * Extracts data from a parsed JSON array.
  29. *
  30. * @param array $data The parsed JSON data (an associative array).
  31. * @param string $key The key to extract the value for.
  32. * @return mixed|null The value associated with the key, or null if the key doesn't exist.
  33. */
  34. function getJsonValue(array $data, string $key)
  35. {
  36. if (isset($data[$key])) {
  37. return $data[$key];
  38. }
  39. return null; // Return null if key is not found.
  40. }
  41. /**
  42. * Extracts nested data from a parsed JSON array.
  43. *
  44. * @param array $data The parsed JSON data.
  45. * @param array $keys An array of keys to traverse the nested structure.
  46. * @return mixed|null The value at the nested path, or null if the path is invalid.
  47. */
  48. function getNestedJsonValue(array $data, array $keys): ?mixed
  49. {
  50. $current = $data;
  51. foreach ($keys as $key) {
  52. if (is_array($current) && isset($current[$key])) {
  53. $current = $current[$key];
  54. } else {
  55. return null; // Path does not exist
  56. }
  57. }
  58. return $current;
  59. }
  60. // Example Usage (for testing)
  61. /*
  62. $json = '{
  63. "name": "John Doe",
  64. "age": 30,
  65. "city": "New York",
  66. "address": {
  67. "street": "123 Main St",
  68. "zip": "10001"
  69. },
  70. "hobbies": ["reading", "hiking"]
  71. }';
  72. $parsedData = parseJson($json);
  73. if ($parsedData) {
  74. echo "Name: " . getJsonValue($parsedData, "name") . "\n";
  75. echo "Age: " . getJsonValue($parsedData, "age") . "\n";
  76. echo "Street: " . getNestedJsonValue($parsedData, ["address", "street"]) . "\n";
  77. echo "Hobbies: " . implode(", ", $parsedData["hobbies"]) . "\n";
  78. } else {
  79. echo "Failed to parse JSON.\n";
  80. }
  81. */
  82. ?>

Add your comment