Hi there,
Just testing JSON in my app. Found this:
$data = json_decode($response->getBody(), true);
$this->assertArrayHasKey('data', $data);
Hope this helps.
Jacob
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I return JSON in a structure like below. It returns users or contacts. The data returned for users is different to contacts.
{
"data": [
{
"id": 1,
"type": "user",
"name": "Joe",
"surname": "Bloggs",
"email": "[email protected]",
"position": "Developer",
"location": "London",
"office": "CS 1",
"reports_to": "Charlie",
"avatar": "",
"private": {
"full_personal_mobile": "+445212121567946",
"emergency_contact_name": "Sarah",
"full_emergency_contact_number": "+44562467856244534",
"emergency_contact_relationship": "Wife"
}
},
{
"id": 24,
"type": "user",
"name": "Simon",
"surname": "Brown",
"email": "[email protected]",
"position": "Manager",
"location": "London",
"office": "CS 1",
"reports_to": "Charlie",
"avatar": "",
"private": {
"full_personal_mobile": "+44546876854676567946",
"emergency_contact_name": "Janet",
"full_emergency_contact_number": "+4456245646724453564",
"emergency_contact_relationship": "Wife"
}
},
{
"id": 48,
"type": "contact",
"name": "steve",
"surname": "smith",
"full_mobile": "+12646847876",
"full_landline": "+24474679468",
"email": "[email protected]",
"position": "Researcher",
}
]
}
Using phpunit I want to check that the data is returned properly so I am using something like this which will work as the fields exist for users and for contacts.
$this->seeJsonStructure([
'data' => [
'*' => [
'id',
'type',
'name',
'surname',
]
]
]);
If I use a field such as 'location' which doesn't exist for contacts the test will fail.
$this->seeJsonStructure([
'data' => [
'*' => [
'id',
'type',
'name',
'surname',
'location',
]
]
]);
I need to be able to check that either the structure of the user or contact is returned in the JSON. Does anyone know to best go about testing something like this?
Many Thanks.
Please or to participate in this conversation.