Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

stwilson's avatar

Testing JSON APIs, specifically: assertJsonStructure

Per the Laravel 5.4 documentation:

$response->assertJsonStructure(array $structure);

...should "assert that the response has a given JSON structure." (documentation ends there)

How would I make the array $structure to represent this json for testing:

{
    "data": {
        "title": "Nam saepe earum molestias consequuntur et doloremque ea.",
        "body": "Consequatur iure omnis distinctio tempore accusamus...",
        "active": false
    }
}

The context of my question is following Laracast Incremental APIs: Level 7: Tests...Readable Ones! Here is the excerpt of my test where I need help filling in the ??:

/** @test **/
public function it_fetches_a_single_lesson()
{
    // arrange
    $this->makeLesson([
        'title'     => 'pets',
        'body'      => 'Millie, Kitcha, Jo Jo, Bill',
        'some_bool' => true
    ]);

    // act
    $response = $this->json('GET', '/api/v1/lessons/1');

    // assert
    $response   ->assertStatus(200)
                ->assertJsonStructure([
                    // ??
                ]);
}
0 likes
5 replies
stwilson's avatar
stwilson
OP
Best Answer
Level 16

Got it:

->assertJsonStructure([
    'data' => [
        'body',
        'title',
        'active'
    ]
])
10 likes
vlauciani's avatar

Hi

is there a way to convert a JSON to PHP array structure?

For example, starting from a JSON like this:

{
  "meta": {
    "total": "1234",
    "last_page": "967",
    "per_page": "4000",
    "current_page": "1",
    "from": "1",
    "to": "4000"
  },
  "data": [
    {
      "book": 10,
      "text": "some text",
      "author": 697

    }
  ]
}

is there a method to obtain:

[
 meta => [
  'total',
  'last_page',
  'per_page',
  'current_page',
  'from',
  'to'
 data => 
  [0] => [
   'book',
   'text',
   'author'
  ]
 ]

it should be useful when you start from API definitions (ex: Swagger) to test you result.

Thank you,

2 likes
driek's avatar

I know this has been asked several months ago but in case someone is looking for it, you can easily convert a response from JSON into an array by calling decodeResponseJson() if you are using the base TestCase class. This method is loaded by the Illuminate\Foundation\Testing\Concerns\MakesHttpRequests trait used in the Illuminate\Foundation\Testing\TestCase class. https://github.com/laravel/framework/blob/5.3/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php#L421 It is not documented in the API because it is a protected method (?)

5 likes
honarmandpooria's avatar

you just need to get into it:

$response->assertJsonStructure([
            "data" => [
                0 => [
                    "a",
                    "b",
                    "c",
                    "d"
                ]
            ]
        ]);

Please or to participate in this conversation.