PHP:使用json文件“尝试获取非对象的属性”

时间:2017-05-01 04:06:55

标签: php 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的建议之间的交叉。必须移动逗号,括号必须更改为大括号。谢谢大家!

1 个答案:

答案 0 :(得分:0)

如果您尝试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": ""
}

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代码: Try this code snippet here

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