我有以下从 API 输出的 JSON 数组。
{
"location": {
"name": "Alanallur",
"region": "Kerala",
"country": "India",
"lat": 11.01,
"lon": 76.33,
"tz_id": "Asia/Kolkata",
"localtime_epoch": 1470998311,
"localtime": "2016-08-12 10:38"
},
"current": {
"last_updated_epoch": 1470997826,
"last_updated": "2016-08-12 10:30",
"temp_c": 28.0,
"temp_f": 82.4,
"is_day": 1,
"condition": {
"text": "Moderate rain",
"icon": "//cdn.apixu.com/weather/64x64/day/302.png",
"code": 1189
},
"wind_mph": 8.1,
"wind_kph": 13.0,
"wind_degree": 340,
"wind_dir": "NNW",
"pressure_mb": 1013.0,
"pressure_in": 30.4,
"precip_mm": 0.0,
"precip_in": 0.0,
"humidity": 79,
"cloud": 0,
"feelslike_c": 32.2,
"feelslike_f": 89.9
}
}
我想使用 JavaScript 将此数组拆分为单独的变量
最佳答案
Json代码
{
posts:[
"location": {
"name": "Alanallur",
"region": "Kerala",
"country": "India",
"lat": 11.01,
"lon": 76.33,
"tz_id": "Asia/Kolkata",
"localtime_epoch": 1470998311,
"localtime": "2016-08-12 10:38"
},
"current": {
"last_updated_epoch": 1470997826,
"last_updated": "2016-08-12 10:30",
"temp_c": 28.0,
"temp_f": 82.4,
"is_day": 1,
"condition": {
"text": "Moderate rain",
"icon": "//cdn.apixu.com/weather/64x64/day/302.png",
"code": 1189
},
"wind_mph": 8.1,
"wind_kph": 13.0,
"wind_degree": 340,
"wind_dir": "NNW",
"pressure_mb": 1013.0,
"pressure_in": 30.4,
"precip_mm": 0.0,
"precip_in": 0.0,
"humidity": 79,
"cloud": 0,
"feelslike_c": 32.2,
"feelslike_f": 89.9
}
}
在 JavaScript 中使用
json.parse()
PHP 代码
<?php
// copy file content into a string var
$json_file = file_get_contents('posts.json');
// convert the string to a json object
$jfo = json_decode($json_file);
// read the title value
$title = $jfo->result->title;
// copy the posts array to a php var
$posts = $jfo->result->posts;
// listing posts
foreach ($posts as $post) {
echo $post->title;
}
?>
希望这有帮助。 :)
关于javascript - 使用 javascript 将 JSON 数组转换为单独的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38911057/