<?php
/**
* Parses JSON API responses.
*
* This function takes a JSON string as input and returns an associative array
* representing the parsed data. Handles basic error checking.
*
* @param string $json_string The JSON string to parse.
* @return array|null An associative array representing the parsed JSON data,
* or null if parsing fails.
*/
function parseJson(string $json_string): ?array
{
// Remove whitespace for cleaner parsing
$json_string = trim($json_string);
// Check if the input is valid JSON
if (empty($json_string)) {
return null; // Return null for empty input
}
$data = json_decode($json_string, true);
if (json_last_error() !== JSON_ERROR_NONE) {
error_log("JSON decode error: " . json_last_error_msg()); // Log the error
return null; // Return null if decoding fails
}
return $data;
}
/**
* Extracts data from a parsed JSON array.
*
* @param array $data The parsed JSON data (an associative array).
* @param string $key The key to extract the value for.
* @return mixed|null The value associated with the key, or null if the key doesn't exist.
*/
function getJsonValue(array $data, string $key)
{
if (isset($data[$key])) {
return $data[$key];
}
return null; // Return null if key is not found.
}
/**
* Extracts nested data from a parsed JSON array.
*
* @param array $data The parsed JSON data.
* @param array $keys An array of keys to traverse the nested structure.
* @return mixed|null The value at the nested path, or null if the path is invalid.
*/
function getNestedJsonValue(array $data, array $keys): ?mixed
{
$current = $data;
foreach ($keys as $key) {
if (is_array($current) && isset($current[$key])) {
$current = $current[$key];
} else {
return null; // Path does not exist
}
}
return $current;
}
// Example Usage (for testing)
/*
$json = '{
"name": "John Doe",
"age": 30,
"city": "New York",
"address": {
"street": "123 Main St",
"zip": "10001"
},
"hobbies": ["reading", "hiking"]
}';
$parsedData = parseJson($json);
if ($parsedData) {
echo "Name: " . getJsonValue($parsedData, "name") . "\n";
echo "Age: " . getJsonValue($parsedData, "age") . "\n";
echo "Street: " . getNestedJsonValue($parsedData, ["address", "street"]) . "\n";
echo "Hobbies: " . implode(", ", $parsedData["hobbies"]) . "\n";
} else {
echo "Failed to parse JSON.\n";
}
*/
?>
Add your comment