Error when get value from json_decode() in php?

2019-07-01 18:41发布

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 !

4条回答
等我变得足够好
2楼-- · 2019-07-01 19:19

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.

查看更多
Fickle 薄情
3楼-- · 2019-07-01 19:24

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'];
查看更多
Luminary・发光体
4楼-- · 2019-07-01 19:30

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/

查看更多
何必那么认真
5楼-- · 2019-07-01 19:34

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

查看更多
登录 后发表回答