简体   繁体   English

Json解析问题,并带有错误尝试获取非对象的属性

[英]Json Parse issue with error Trying to get property of non-object

I want to parse following json for value of 我想解析以下json的值

JSON (saved in my.json): JSON(保存在my.json中):

{
"mackoniv":{"entry":"","lastExit":"","userId":"OPENGOVTJOBS","userNick":"mack"},
"johanna":{"entry":"","lastExit":"","userId":"FREEJOBALERT","userNick":"jone"}
}

Code used : 使用的代码:

$json = file_get_contents('my.json');
$json_data = json_decode($json,true);
$userToCheck='johanna';
echo 'userId'.$json_data->$userToCheck->userId;

The above code gives error "Trying to get property of non-object", which i understand as $userToCheck isnt an object of $json_data but how do i access the data of "mackoniv" or even "johanna" when userToCheck part is not to be hardcoded. 上面的代码给出了错误“试图获取非对象的属性”,我将其理解为$ userToCheck不是$ json_data的对象,但是当userToCheck部分不执行该操作时,如何访问“ mackoniv”甚至“ johanna”的数据被硬编码。

If i try following way, it gives same error. 如果我尝试以下方法,它将给出相同的错误。

echo 'userId'.$json_data[$userToCheck]['userId'];

first of all json_decode($jsondata, true); 首先json_decode($jsondata, true); would return an array. 将返回一个数组。 try to var_dump your $json to make sure you've got the file and then var_dump $json_data. 尝试var_dump $ json以确保您有文件,然后var_dump $ json_data。

If you write it like below it should work. 如果您像下面这样写,它应该可以工作。

        $json = file_get_contents('my.json');
        $json_data = json_decode($json, true);
        $userToCheck = 'johanna';
        echo 'userId = ' . $json_data[$userToCheck]['userId']; 

Basically change the line: 基本上换行:

echo 'userId' . $json_data->$userToCheck->userId; 

with: 与:

echo 'userId = ' . $json_data[$userToCheck]['userId'];

if json_decode second paramether is true, it returns an array, if it is false (default), returns an object. 如果json_decode第二个paramether为true,则返回一个数组;如果为false(默认值),则返回一个对象。 So, if you want to use it as an object, just decode it like: $json_data = json_decode($json); 因此,如果您要将其用作对象,只需对其进行解码即可: $json_data = json_decode($json); . If this doesn't work, check what echo json_last_error_msg(); 如果这不起作用,请检查echo json_last_error_msg(); returns. 返回。 If it returns "No error", then the problem is that your file_get_contents() is not refering to the correct file. 如果返回“ No error”,则问题是您的file_get_contents()没有引用正确的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM