2

I have a JSON string that I would like to include as a value in a larger JSON object that I am creating from an array. How can I create the larger JSON object without php escaping the string, and without having to decode the previously encoded string?

For example, if my JSON string is:

$encoded_already = '{"encoded_key": "encoded_value"}';

And I would like to include it in my array and json_encode() it:

$new_array = array(
    "some_other_key" => $some_value,
    "premade_data" => $encoded_already
);
$output = json_encode($new_array);

but I want to have the $encoded_already string be included as actual JSON, not just an escaped string.

1 Answer 1

2

Here's an idea: place a token as an attribute value and then use str_replace on it.

Works only if $token doesn't appear anywhere in your JSON.

$token = '%%%';
$output = str_replace( '"' . $token . '"', $encoded_already, json_encode( array(
    "some_other_key" => $some_value,
    "premade_data" => $token
) );
Sign up to request clarification or add additional context in comments.

3 Comments

Added $new_array =. :) You might want to replace '%%%' with uniqid().
OK, I was thinking about doing that but wasn't sure if there was a better way. That's going to be annoying with multiple strings though...
sometimes dumb answers are the smart ones

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.