3

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

Danack
  • 24,939
  • 16
  • 90
  • 122
Sree
  • 41
  • 1
  • 1
  • 8

4 Answers4

4

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
}
Alireza
  • 1,428
  • 4
  • 21
  • 33
1

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

Aman Virk
  • 3,909
  • 8
  • 40
  • 51
0

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
        )

)
Dino Babu
  • 5,814
  • 3
  • 24
  • 33
-1

For this case, I prefer to add curly brackets before and after the string. It allows me then to use json_decode($json, true); which is my favorite way to interact with json variables.

  $my_json = '[{"location":[{"building":["Default Building"],"name":"Default Location"}],"name":"Default Organization"}]';
  $json = json_decode('{ "data":'.$my_json.'}', true);
  $my_data = $json['data'][0];
  print_r($my_data['location']);
  echo $my_data['location'][0]['building'][0];
Ibrahim
  • 6,006
  • 3
  • 39
  • 50