Error when get value from json_decode() in php?

杀马特。学长 韩版系。学妹 提交于 2019-12-10 19:19:05

问题


I have a sample code:

$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 !


回答1:


Try this:

echo $data->{'2G Network'};

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.




回答2:


Brad solution is perfect, and if you want similar from an array you can do it like:

$description = '{"2G Network":"GSM 850 / 900 / 1800 / 1900 ","3G Network":"HSDPA 850 / 900 / 1700 / 1900 / 2100 "}';
$data = json_decode($description, true);
echo $data['2G Network'];



回答3:


You can either remove the space between 2G and Network or decode the json to an array using json_decode($description, true)




回答4:


you may call functions to remove the spaces in the JSON

see below http://www.pukkared.com/2010/02/removing-extra-white-space-before-returning-json-data/



来源:https://stackoverflow.com/questions/11480954/error-when-get-value-from-json-decode-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!