使用方括号解码JSON [重复]

gab6jxml  于 2023-04-08  发布在  其他
关注(0)|答案(4)|浏览(201)

此问题已在此处有答案

How to extract and access data from JSON with PHP?(1个答案)
2天前关闭。
我试着解码这个json,但没有运气,这些方括号让我困惑任何帮助将不胜感激,这里是我的json

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

谢谢你

pkbketx9

pkbketx91#

试试这个:

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

uujelgoq2#

你的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;

对象将只返回第一项,如果数组有多个值,则使用foreach

v1l68za4

v1l68za43#

这是一个有效的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
        )

)
trnvg8h3

trnvg8h34#

在这种情况下,我更喜欢在字符串前后添加花括号。它允许我使用json_decode($json, true);,这是我最喜欢的与json变量交互的方式。

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

相关问题