简体   繁体   中英

How to Parse this JSON (PHP & JSON_DECODE)

I am using the following API: https://openweathermap.org and it gives a JSON response to get the current weather.

{  
   "coord":{  
   "lon":
   "lat":
},
"weather":[  
   {  
     "id":521,
     "main":"Rain",
     "description":"shower rain",
     "icon":"09n"
  }
],
"base":"stations",
"main":{  
  "temp":289.22,
  "pressure":1004,
  "humidity":82,
  "temp_min":288.15,
  "temp_max":290.15
},
"visibility":10000,
"wind":{  
  "speed":4.1,
  "deg":210
},
"clouds":{  
  "all":100
},
"dt":1501793400,
"sys":{  
  "type":1,
  "id":5060,
  "message":0.0039,
  "country":"GB",
  "sunrise":1501734589,
  "sunset":1501790444
},
"id":3333126,
"name":"Borough of Blackburn with Darwen",
"cod":200
}

What is the correct way to go about getting the main and description in the JSON?

I have attempted the code below but it doesn't work:

$url = "http://api.openweathermap.org/data/2.5/weather?lat=" . $latitude . "&lon=" . $longitude . "&APPID=71f4ecbff00aaf4d61d438269b847f11";
$dirty_data = file_get_contents( $url );

$data = json_decode( $dirty_data );
echo $data['weather']['main'];

When using json_decode() to convert json data to php type, it will always convert it into an object. To be clear you can access weather's main and description property like this:

echo $data->weather[0]->main // outputs main
echo $data->weather[0]->description // outputs description

Update:

Besides you can also convert data into an associative array by passing bool(true) $assoc argument to the json_decode() function.

$data = json_decode( $dirty_data, true );

And extract your data like this:

echo $data['weather'][0]['main']; // for main
echo $data['weather'][0]['description']; // for description

Yo can always do var_dump($data) to see what you have and how to access it.
json_decode returns a stdClass not an array.
$data->weather[0]->main;
Should be the right thing.
{} symbolizes an object and [] symbolizes an array. Notice weather:[{...}] which means weather is an array of objects.

Try

$data = json_decode( $dirty data, true)

It doesn't convert to an object if you supply the true argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM