PHP:"Trying to get property of non-object" json 文件



我正在尝试从同一目录中的JSON文件中获取值,但请继续获取"试图获取非对象的属性"通知。我对JSON的经验不足,无法发现文件和我使用的引用之间的任何差异。我已经进行了一些研究,研究了这里的类似问题,主要查看使用{}和[],但是我尝试过的任何事情都没有起作用。如果有人能提供帮助,将不胜感激。

<?php
$myJSON = file_get_contents("myfile.json");
$phpVersion = json_decode($myJSON);
$name = $phpVersion->name;
$birthdate = $phpVersion->birthdate;
$city = $phpVersion->address->city;
$state = $phpVersion->address->state;
?>

和myfile.json是:

{
    "name": "First Last",
    "phone_number": "123-456-7890",
"birthdate": "01-01-1985",
"address":
    [
        "street": "123 Main St",
        "city": "Pleasantville",
        "state": "California",
        "zip": "99999",
    ]
"time_of_death": ""
}

我有点不确定这是地址的正确格式,但我非常确定这不是引起问题的原因。我将收到PHP文件的所有四行通知。谢谢!

编辑:使它起作用。最终是Sahil和Frenchmajesty的建议之间的十字架。必须移动逗号,并且必须将支架更改为牙套。谢谢大家!

您的JSON not valid 如果您尝试使用json_decode,希望您会得到此错误。

错误:数组值分离器','预期

{
    "name": "First Last",
    "phone_number": "123-456-7890",
"birthdate": "01-01-1985",
"address":
    [ //<---- issue is here
        "street": "123 Main St",
        "city": "Pleasantville",
        "state": "California",
        "zip": "99999",//<---- issue is here
    ] //<---- issue is here
"time_of_death": ""
}

a valid json 可以是这个

{
    "name": "First Last",
    "phone_number": "123-456-7890",
    "birthdate": "01-01-1985",
    "address": {
        "street": "123 Main St",
        "city": "Pleasantville",
        "state": "California",
        "zip": "99999"
    },
    "time_of_death": ""
}

php代码:尝试此代码代码段

<?php
ini_set('display_errors', 1);
$json='{
    "name": "First Last",
    "phone_number": "123-456-7890",
    "birthdate": "01-01-1985",
    "address": {
        "street": "123 Main St",
        "city": "Pleasantville",
        "state": "California",
        "zip": "99999"
    },
    "time_of_death": ""
}';
$phpVersion=json_decode($json);
echo $name = $phpVersion->name;
echo $birthdate = $phpVersion->birthdate;
echo $city = $phpVersion->address->city;
echo $state = $phpVersion->address->state;

相关内容

最新更新