T
T
tincap2017-02-10 14:50:00
PHP
tincap, 2017-02-10 14:50:00

How to get a stdClass object that has a space in its name?

Hello. I use API of one service. In response to the request, it returns Json to me. After decoding, this is the result:
stdClass Object
(
[response] => 1
[counts People] => 1849
)
How do I get the "counts People" object?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Mikhail Osher, 2017-02-10
@tincap

<?php

$rawJson = '{"response":1,"counts People":1849}';
$jsonObj = json_decode($rawJson);
$jsonArray = json_decode($rawJson, true);

var_dump($jsonObj, $jsonArray);
var_dump($jsonObj->{'counts People'});
var_dump($jsonArray['counts People']);

object(stdClass)#1 (2) {
  ["response"]=>
  int(1)
  ["counts People"]=>
  int(1849)
}
array(2) {
  ["response"]=>
  int(1)
  ["counts People"]=>
  int(1849)
}
int(1849)
int(1849)

M
Melkij, 2017-02-10
@melkij

It is often more convenient to work with an array. See second parameter json_decode.
And so, it is possible to use the syntax:
$json->{'some invalid-name'}

A
Anton Shamanov, 2017-02-10
@SilenceOfWinter

1. it's not an object
2. convert it to an associative array and access the array element

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question