r/PHPhelp • u/ManyInteresting3969 • Apr 15 '26
json_decode troubles
Hey there, I am passing some nested array via AJAX and Javascript and using JSON.stringify to pass the string. However, on the php side, json_decode isn't helping.
I can see in the logs that the string that JSON.stringify returns is "[[\"user\",\"say hello\"]]", a lovely valid JSON string.
But when I pass it through , I get a Syntax error.
$m_str = $_POST['messages'];
// $m_str = "[[\"user\",\"say hello\"]]";
$messages = json_decode($m_str, true);
echo json_last_error_msg();
Oddly, if I uncomment the second line, there is no error. Do I have to do something to $m_str before I can decode it?
This is in the functions.php file of a Wordpress theme, hopefully that doesn't matter but it just occured to me it might.
Thanks for reading,
Solved -- had to wrap the messages in stripslashes.
5
u/HolyGonzo Apr 15 '26
I would bet that your AJAX method is already stringify-ing or escaping data (sometimes this is part of AJAX libraries that try to manage everything for you), so if you are stringify-ing it yourself, it might be encoding twice.
Like u/colshrapnel said, don't try to fix this on the receiving side (PHP) with stripslashes, but find and fix it on the sending side.
2
u/SZenC Apr 15 '26
Have you added those backslashes for formatting on Reddit? Or are those presents in your application as well?
10
u/colshrapnel Apr 15 '26
Instead of "wrapping in stripslashes" you should find the place where these parasite slashes were added and fix there.
Just running arbitrary stripslashes on JSON is the last thing you want to do, it will ruin correct json for sure.
Start from doing
var_dump($_POST['messages']);1
u/MartinMystikJonas Apr 15 '26
My guess would be double escaping on sender side. You probably send not string that contains " character but string that contains both \ and " in string itself.
-2
u/xreddawgx Apr 15 '26
You can also use json_encode