I’m working with a JSON string that contains Unicode-escaped characters, such as u003C, and I want to decode the JSON into an associative array without converting these Unicode characters to their literal equivalents (e.g., u003C should stay as it is and not convert to <).
Here’s a simplified example of my JSON and code:
// Original JSON string
$json = '{"Code_Injecting":{"Code":"u003Cstyleu003E div#example { display: none; }u003C/styleu003E"}, "RemoveKey":"removeValue"}';
// Step 1: Decode JSON to an array
$array = json_decode($json, true);
// Check if decoding was successful
if (json_last_error() !== JSON_ERROR_NONE) {
die('Error decoding JSON: ' . json_last_error_msg());
}
// Step 2: Unset the key "Code_Injecting" if it exists
if (isset($array['Code_Injecting'])) {
unset($array['Code_Injecting']);
}
// Step 3: Encode it back to JSON while preserving Unicode-escaped characters
$newJson = json_encode($array, JSON_UNESCAPED_SLASHES);
// Output the final JSON
echo $newJson;
// Expected Output:
// {"Code_Injecting":{"Code":"u003Cstyleu003E div#example { display: none; }u003C/styleu003E"}}
I need the Unicode-escaped characters (like u003C) to remain unchanged when decoding JSON. Is there a way to achieve this in PHP?
I’ve tried looking into JSON_UNESCAPED_UNICODE during encoding but didn’t find an equivalent for decoding. Any help or suggestions would be appreciated!