json_decode is not working on my variable but is on its content

json, php

Solution

because your string is json_encoded twice, so you need to decode it twice.

string(133) ""[{\"lang_id\": \"1\", \"naam\": \"dsfsdfds\", \"mail\": \"dsfdsfs\"}, {\"lang_id\": \"1\", \"naam\": \"dfsd\", \"mail\": \"dfds\"}]""

if you look in the string above you see that all he quotes are escaped and there is a double quote in the beginning and in the end. so this means if you json decode you get an string withouth the escaped quotes.

if you decode again the string will be decoded to an array.

json_decode('"[12,24,32]"'); //php string:  [12,24,32]
json_decode('[12,24,32]'); //php array(12, 24, 32);

Problem

I have the following piece of code: ``` $param = $params[0]; var_dump($param->getValue()); $test = json_decode($param->getValue()); var_dump($test); ``` my first var_dump returns the following: ``` string(133) ""[{\"lang_id\": \"1\", \"naam\": \"dsfsdfds\", \"mail\": \"dsfdsfs\"}, {\"lang_id\": \"1\", \"naam\": \"dfsd\", \"mail\": \"dfds\"}]"" ``` the seconde one is returning the following: ``` string(107) "[{"lang_id": "1", "naam": "dsfsdfds", "mail": "dsfdsfs"}, {"lang_id": "1", "naam": "dfsd", "mail": "dfds"}]" ``` and the value is saved in my DB like this: ``` "[{\"lang_id\": \"1\", \"naam\": \"dsfsdfds\", \"mail\": \"dsfdsfs\"}, {\"lang_id\": \"1\", \"naam\": \"dfsd\", \"mail\": \"dfds\"}]" ``` Now my question is: Why is it returning a string after the json_decode? I have absolutely no idea what i'm doing wrong and the strangest thing is that if i replace the variable with the actual value of that variable then the decode is correct: ``` $test = json_decode("[{\"lang_id\": \"1\", \"naam\": \"dsfsdfds\", \"mail\": \"dsfdsfs\"}, {\"lang_id\": \"1\", \"naam\": \"dfsd\", \"mail\": \"dfds\"}]"); ``` returns ``` array(2) { [0]=> object(stdClass)#3255 (3) { ["lang_id"]=> string(1) "1" ["naam"]=> string(8) "dsfsdfds" ["mail"]=> string(7) "dsfdsfs" } [1]=> object(stdClass)#3256 (3) { ["lang_id"]=> string(1) "1" ["naam"]=> string(4) "dfsd" ["mail"]=> string(4) "dfds" } } ``` What am i doing wrong?

Original source