从php中的json_decode()获取值时出错?
问题描述:
我有一个示例代码:
$description = '{"2G Network":"GSM 850 / 900 / 1800 / 1900 ","3G Network":"HSDPA 850 / 900 / 1700 / 1900 / 2100 "}';
$data = json_decode($description);
echo $data->2G Network;
// OR echo $data['2G Network'];
结果是错误,如何解决!
result is error, how to fix it !
答
尝试一下:
echo $data->{'2G Network'};
问题不在于JSON,而是您尝试访问的对象属性中有一个空格.如果使用花括号{
}
,则可以使用字符串来命名要获取/设置的属性.
The problem wasn't with JSON, but that you had a space in the object property you were trying to access. If you use curly braces {
}
, then you can use strings to name the property you want to get/set.