0

I have a string on my databas, that I'm trying to insert into a json object as an Array, not a string..:

$arrayInString = "[2,3,5,5,6]"; // this comes from the database
$jsonObject = array('numbers' => $arrayInString);
$json = json_encode($jsonObject, JSON_UNESCAPED_SLASHES);
echo $json;

When I execute this.. my Json object is..

numbers: "[2,3,5,5,6]";

and not

numbers: [2,3,5,5,6];

Like I originally wanted.. can't get this to work, can anyone help?

2 Answers 2

2

Like was said you need to decode the passed data from the database and then build your array output. Something like this:

    $arrayInString = "[2,3,5,5,6]"; // this comes from the database

    // decode the JSON from the database as we build the array that will be converted back to json
    $jsonObject = array('numbers' => json_decode($arrayInString));

    echo json_encode($jsonObject, JSON_UNESCAPED_SLASHES);

The slightly modified code above outputs:

{"numbers":[2,3,5,5,6]}
Sign up to request clarification or add additional context in comments.

Comments

2

You need to json_decode your $arrayInString variable before you add it to the associative array.

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.