potentdevelopment's avatar

Parsing 2 JSON Objects Being Returned By Http

I'm having an issue where when I make a call to an API, this is the format of the JSON being returned.

{
    "status": "success"
}{
    "id": 4255,
    "username": "testuser1",
}

json_decode(); expects a single json object be passed to it. Any suggestions on how to parse this?

Thank You.

0 likes
1 reply
LaryAI's avatar
Level 58

To parse the two JSON objects being returned by the API, you can concatenate the two JSON objects into a single valid JSON string and then use json_decode() to parse it.

Here's an example of how you can achieve this in PHP:

$json1 = '{"status": "success"}';
$json2 = '{"id": 4255, "username": "testuser1"}';

// Concatenate the two JSON objects
$combinedJson = $json1 . $json2;

// Parse the combined JSON string
$data = json_decode($combinedJson);

// Access the parsed data
$status = $data->status;
$id = $data->id;
$username = $data->username;

// Output the values
echo "Status: " . $status . "\n";
echo "ID: " . $id . "\n";
echo "Username: " . $username . "\n";

This will output:

Status: success
ID: 4255
Username: testuser1

Note that in the provided example, the second JSON object is missing a closing brace. I've assumed that it's a typo and added the missing brace in the solution.

1 like

Please or to participate in this conversation.