Home > Software engineering >  Read a JSON data value with mixed number and letter in key in PHP
Read a JSON data value with mixed number and letter in key in PHP

Time:10-21

I am stuck with this issue. I am trying to read data from openweathermap.org weather data API. One of the values, rainfall amount, is keyed with a digit and letter in the key. And PHP is throwing errors at me if I try to read it. Here is the code I'm trying to use.

$rainAmount = $data->hourly[$hour]->rain->1h;

and here is the JSON file (a portion of it anyways).

"rain": {
    "1h": 1.78
}

This is data provided by the API so I can't just change the key that's used. Here is the PHP error

PHP Parse error: syntax error, unexpected integer "1", expecting identifier or variable or "{" or "$" in /home/

It's pretty obvious it is the digit in the key that is the issue. But how else do I read the value?

Thanks in advance.

CodePudding user response:

Did you try:

$string = '{
  "rain": {
        "1h": 1.78
  },
}';

$arr_weather = json_decode($string, true);

print $arr_weather['rain']['1h'];

The second parameter from json_decode(,, true is a bool to decode the data as an associative array. Please read more here about json_decode:

https://www.php.net/manual/en/function.json-decode.php

If you still want to work with your response as an object you can use the curly braces like this:

$string = '{
      "rain": {
            "1h": 1.78
      },
    }';
    
$weatherObject = json_decode($string);

print $weatherObject->rain->{'1h'};

But in this case, you have to know that if your key is a number only, it will not work, like $weatherObject->rain->{'12'} - So I recommend using the data as an array, like in the first example.

  • Related