Adding square brackets around json

I have a json response which is

{
    "refresh_token": "s34Ap9VaYVIh8SSzcO2tIgjc985JLbzw",
    "token_type": "bearer",
    "access_token": "MPwvR52wNIEZIVh30z2u5IBSVrUaaP4H",
    "expires_in": 172800
}

When I save to the database I need it to have square brackets around it.

[{
    "refresh_token": "s34Ap9VaYVIh8SSzcO2tIgjc985JLbzw",
    "token_type": "bearer",
    "access_token": "MPwvR52wNIEZIVh30z2u5IBSVrUaaP4H",
    "expires_in": 172800
}]

I prepare the JSON before saving it so it add “” and blackslashses. When I save it, it is adding an addiitonal " on the inside of the square brackets and an /n before the last square bracket.

["{\"refresh_token\":\"g32XZgJjYj1cXVmt8yhNqzt45YM1OyML\",\"token_type\":\"bearer\",\"access_token\":\"RTCZ18VAqoRGATpX8jJ2WoKRLf6RMybT\",\"expires_in\":172800}\n"]

So when I try to extract the data I am having to write all kinds of funny PHP and js to interact with it. No idea why it keeps adding this. Any ideas?

Figured it out. I needed to use json_decode on the response JSON before I could add the JSON to a new array then encode it before saving to db.

In case it helps anyone.

$json_reponse; // contains json in api response using CURL
$decode_json_response = json_decode($json_response); // now decode it
$update_json = array($decode_json_response); // update the json
$new_json = json_encode($update_json); // encode it

Final Output

[{
    "refresh_token": "s34Ap9VaYVIh8SSzcO2tIgjc985JLbzw",
    "token_type": "bearer",
    "access_token": "MPwvR52wNIEZIVh30z2u5IBSVrUaaP4H",
    "expires_in": 172800
}]

Can you replace these two lines

$decode_json_response = json_decode($json_response); // now decode it
$update_json = array($decode_json_response); // update the json

with this one

$update_json = json_decode($json_response, true); // now decode it into an associative array

and decode it directly into an array? (I’ve done nothing with JSON so I may be missing something).

Instead of decoding it, adding it to an array and encode it back, you can more easily just add the square brackets inside the string.

"[{\"refresh token\"….. }]"

…
$json_response = "[".$json_response."]"

3 Likes

@m_hutley yeah, I supposed that would work too. I actually needed to extract data from the JSON first before encoding it, which was not mentioned in my post. But yeah your approach is easy.