希望对我的编码有所帮助。
我正在尝试使用一些 jquery 编码来从在线天气 api 获得的 JSON 响应中提取特定对象。
这是我从代码中获得的 JSON 响应:
{
"coord":
{
"lon": -4.53,
"lat": 55.64
},
"sys":
{
"message": 0.0069,
"country": "GB",
"sunrise": 1388306829,
"sunset": 1388332429
},
"weather": [
{
"id": 501,
"main": "Rain",
"description": "moderate rain",
"icon": "10n"
}],
"base": "cmc stations",
"main":
{
"temp": 281.63,
"pressure": 997,
"humidity": 87,
"temp_min": 281.15,
"temp_max": 282.15
},
"wind":
{
"speed": 8.7,
"deg": 170
},
"rain":
{
"3h": 11
},
"clouds":
{
"all": 40
},
"dt": 1388357400,
"id": 2645605,
"name": "Kilmarnock",
"cod": 200
}
通过上面的 JSON 响应,我试图捕获 sys/country 中的 GB 和 Weather/main 中的 Rain。
这是我一直在使用的代码:
<script> jQuery(document).ready(function($) {
$.ajax({
url : "http://api.openweathermap.org/data/2.5/weather?lat=55.6409921&lon=-4.5282146",
dataType : "jsonp",
success : function(parsed_json) {
var locations = parsed_json['name'],
country = parsed_json['sys.country']
main = parsed_json['weather.main'];
var min = parsed_json['sys.country'];
alert("Current locaiton is " + locations );
alert("Current country is " + country);
alert("Current weather is " + main );
console.log('<p>'+country+'</p>');
console.log('<p>'+main+'</p>');
} }); });
虽然我一直在搞乱代码,但位置有效,但对于国家和主要,我要么得到 [Object object] 要么未定义,所以在这一点上我没有任何线索。
非常感谢任何帮助。
最佳答案
sys.country
不是关键,您需要访问country = parsed_json.sys.country
parsed_json['sys.country']
在 parsed_json
对象中查找键 sys.country
,即您想要的值对象sys
country
另请注意,天气是一个数组,因此您需要使用 main = parsed_json.weather[0].main
等索引来访问 main
属性
演示:Fiddle
关于jquery - 使用Jquery显示特定的JSON对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20832389/