1

I have just been bashing my head against a brick wall for several hours trying to use the json_decode() function in PHP. The same problem has appeared on Stack Overflow many times, for example here and here.

The solution was that, as stated in the docs, if you want to get an associative array from a JSON object, you need to include a second, optional true parameter in your function call, like this:

$assoc_array = json_decode($the_JSON,true);

On the other hand, leaving this parameter out returns an object instead:

$php_objest = json_decode($the_JSON);

This is most annoying for me because it's a problem I've solved before some time ago, but forgot.

Do people agree that having this defaulting to true rather than false reflects the majority of use-cases?

 

Edit: As requested below, the use-case that caused this error (similar to what I've done in the past) was trying to decode a JSON object, add/re-arrange some values, and then re-encode. A code example is:

$the_hardcoded_json_string = "{\"a\":60,\"vi\":0,\"is\":0}";
$the_associative_array = json_decode( $the_hardcoded_json_string, true );
$the_associative_array["c"] = 758;
$the_new_json_string = json_encode( $the_associative_array );
2
  • No - can you expand on why this would want a false parameter? Commented May 6, 2015 at 10:18
  • Can you elaborate a little like how you encoding and decoding? If possible plz provide code sample. Commented May 6, 2015 at 10:20

1 Answer 1

2

I don't know if this is the right place here to discuss php's default parameters but if i like to change it i would do it like this:

function my_json_decode($json, $assoc=true, $depth=512, $options=0) {
    return json_decode($json, $assoc, $depth, $options);
} 

I hope i understood your question correctly. Please correct me if i don't. I am not shure if the majority of use-cases need the assoc-argument set to true. But I fear there will be a lot of trouble if they change it to true right now, because a lot of code needs to be rewritten.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.