如何在页面上显示 JSON 并从中读取特定值

How to show JSON on a page and also read a particular value from it

我希望我的代码获取 JSON 并读取伦敦的温度值。

如有任何帮助,我们将不胜感激。

但是我有两个问题,获取的数据显示:[object Object]

  1. 如何修复?
  2. 如何让它在 main 和 temp 中获取伦敦的温度值。

可能是这样的:

data.["main"].temp

这是伦敦的开尔文温度,277.21。

我的JSON:

{
    "coord": { "lon": -0.1257, "lat": 51.5085 },
    "weather": [{ "id": 800, "main": "Clear", "description": "clear sky", "icon": "01n" }],
    "base": "stations",
    "main": { "temp": 277.21, "feels_like": 275.36, "temp_min": 274.4, "temp_max": 279.13, "pressure": 1042, "humidity": 93 },
    "visibility": 9000,
    "wind": { "speed": 2.06, "deg": 230 },
    "clouds": { "all": 9 },
    "dt": 1642014889,
    "sys": { "type": 2, "id": 2019646, "country": "GB", "sunrise": 1641974505, "sunset": 1642004119 },
    "timezone": 0,
    "id": 2643743,
    "name": "London",
    "cod": 200
}

我的错误代码:

 $.ajax({
            url: "https://api.openweathermap.org/data/2.5/weather?q=London&appid=a7a01852c805157a4c8334e87e39c75c",
            cache: false,
            dataType: "json",
            complete: function(data) {
               

                tempLondon = data;
             
                 $('#tempLondon').append('The temperature is ' + tempLondon );
                 console.log(tempLondon);
            }
        });

当您将对象转换为字符串时,例如尝试将其直接插入到标记中,它会变成 '[object Object]'。虽然这肯定不直观,但您必须记住,对象可以包含循环引用,因此可能无法将它们转换为字符串。

但是,您可以改为使用 JSON.stringify 将您的对象转换为 JSON 字符串并将其打印到控制台:

console.log(JSON.stringify(tempLondon, null, '\t'));

因为您的对象首先是从 JSON 字符串构造的(这发生在 jQuery 的 $.ajax 函数的幕后),它不能包含任何循环引用,因此从中构造 JSON 字符串不会有任何问题。

如果要检索温度本身,只需使用点符号:

console.log(tempLondon.main.temp);

试试这个

$.ajax({
type: 'GET',
url: "https://api.openweathermap.org/data/2.5/weather?q=London&appid=a7a01852c805157a4c8334e87e39c75c",
dataType: "json",
success: function(data) {

console.log(JSON.stringify(data));
$('#tempLondon').html('The temperature is ' + data.main.temp );
 
},
error: function (error) {
console.log(JSON.stringify(error));
}     
  });
 

以后不要把点和括号放在一起。

有效

 data.main.temp
//or 
data["main"].temp

无效

data.["main"].temp