使用方括号解码JSON

时间:2013-03-21 07:07:51

标签: php json echo

我试图解码这个json,但没有运气,这些方括号让我感到困惑 任何帮助将不胜感激,这是我的json

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

谢谢

3 个答案:

答案 0 :(得分:2)

试试这个:

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

json_decode返回数组或object。您可以使用var_export而不是echo

进行打印

您可以访问值:

$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
}

答案 1 :(得分:1)

您的json有效,可能是您在访问数组内的对象时遇到问题。

print_r永远是理解数组结构的好朋友。试试这个

    $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;

位置0处的对象仅返回第一个项目,如果您的数组有多个值,则使用foreach

答案 2 :(得分:0)

似乎是一个有效的JSON。

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

//输出

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

                            [name] => Default Location
                        )

                )

            [name] => Default Organization
        )

)