Sree
Sree

Reputation: 41

Decode JSON with square brackets

I have tried to decode this json,but no luck,these square brackets are making me confused any help would be appreciated,here is my json

[{"location":[{"building":["Default Building"],"name":"Default Location"}],"name":"Default Organization"}]

Thank you

Upvotes: 3

Views: 10803

Answers (3)

Alireza
Alireza

Reputation: 1438

try this:

var_export( json_decode( '[{"location":[{"building":["Default Building"],"name":"Default Location"}],"name":"Default Organization"}]' )  );

json_decode return array or object . you can print it with var_export not echo

and you can access to values :

$items = json_decode('[{"location":[{"building":["Default Building"],"name":"Default Location"}],"name":"Default Organization"}]');

foreach( $items as $each ){
  echo $each->location[0]->building[0];
  echo '<hr />';
  echo $each->location[0]->name;
  echo '<hr />';
  echo $each->name; // default organization
}

Upvotes: 4

Aman Virk
Aman Virk

Reputation: 3977

Your json is valid , might be you are facing problem while accessing the objects inside the array.

print_r is always a good friend to understand array structure . try this

    $json = '[{"location":[{"building":["Default Building"],"name":"Default Location"}],"name":"Default Organization"}]';
$decoded = json_decode($json);

echo '<pre>';
print_r($decoded);

$location = $decoded[0]->location;
$building = $location[0]->building[0];
$name = $location[0]->name;

Object at place 0 will only return the first item , if your array has multiple values then use foreach

Upvotes: 1

Dino Babu
Dino Babu

Reputation: 5809

Seems its a valid JSON.

$my_json = '[{"location":[{"building":["Default Building"],"name":"Default Location"}],"name":"Default Organization"}]';
$my_data = json_decode($my_json);
print_r($my_data);

// Output

Array
(
    [0] => stdClass Object
        (
            [location] => Array
                (
                    [0] => stdClass Object
                        (
                            [building] => Array
                                (
                                    [0] => Default Building
                                )

                            [name] => Default Location
                        )

                )

            [name] => Default Organization
        )

)

Upvotes: 0

Related Questions