2017-05-01 76 views
0

我试图从同一个目录中的JSON文件获取值,但不断收到“尝试获取非对象的属性”通知。我对JSON很缺乏经验,并且无法发现我的文件和我正在使用的参考文件之间的差异。我已经做了一些研究,看看这里的类似问题,主要看使用{}和[],但没有任何我尝试过的。如果任何人都可以帮助它将不胜感激。PHP:“尝试获取非对象的属性”与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文件所有四行的通知。谢谢!

编辑:得到它的工作。它最终成为萨希尔和法国国王陛下建议的一个交叉点。逗号必须移动,括号必须改为括号。感谢大家!

+0

这是什么'的var_dump($ phpVersion)'显示? – Jocelyn

+0

取出逗号后的逗号,并将其放在]之后。这就是为什么你的JSON对象被破坏的原因 – FrenchMajesty

+0

var_dump显示NULL。 – cec526

回答

0

JSONnot valid如果您尝试json_decode,希望你会得到这个错误。

Error: array value separator ',' expected

{ 
    "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; 
+0

完成这些更改后,我仍然收到相同的通知,并且var_dump($ phpVersion)仍显示NULL。所以它仍然不喜欢我的JSON文件。 – cec526

+0

@ cec526好吧没问题,我会给你完整的演示.. –

+0

不要担心它。我得到了它的工作。将更新主帖子。 – cec526

相关问题