2

let's suppose I have the following array:

$res['results']='{"key":"value"}';
$res['status']='OK';

and I json_encode that array:

var_dump(json_encode($res));

This is the result (double quotes are escaped):

{"results":"{\"key\":\"value\"}","status":"OK"}

But I want this result (double quotes not escaped):

{"results":"{"key":"value"}","status":"OK"}

What's the correct way to accomplish my goal, supposing that the array is a bit more complicated and I don't know which values are json themselves?

Thanks very much

1 Answer 1

1

You've embedded json in a php string. PHP doesn't know what JSON is, and will treat that json-in-string as it would any other string - any json metacharacters will be quoted when you json_encode() again. e.g. it'll just double-encode.

You need to decode the json string, store the decoded data structure, then re-encode the entirety:

$res['results']=json_decode('{"key":"value"}');
                ^^^^^^^^^^^^-----------------^
$res['status']='OK';
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah I know, I guess it's the only option? I was looking for a general solution in case you don't know that that value will be a json (suppose it's a variable coming from somewhere else...).
well, your desired result is invalid json anyways. it would blow up any json parser you fed it to.

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.