我是 JSON、node.js 和 javascript 的新手...我有一个小型 node.js 服务器,它从 openweathermap.org 获取一个 JSON 对象(下面名为 weatherData),我试图让它只显示JSON 对象的特定部分(名为“temp”的部分)。到目前为止我用过:
var tempString = JSON.stringify(weatherData);
然后我使用字符串的搜索和子字符串方法来获取我的信息,但一定有更简单的方法吧?如何在不使用字符串方法的情况下仅显示临时部分?
编辑:当我对整个事情进行字符串化时,我得到了这个
"{\"coord\":{\"lon\":-75.7,\"lat\":45.41},\"sys\":{\"type\":3,\"id\":119304,\"message\":0.0297,\"country\":\"CA\",\"sunrise\":1413804390,\"sunset\":1413842906},\"weather\":[{\"id\":802,\"main\":\"Clouds\",\"description\":\"scattered clouds\",\"icon\":\"03n\"}],\"base\":\"cmc stations\",\"main\":{\"temp\":273.05,\"humidity\":84,\"pressure\":1012.188,\"temp_min\":273.05,\"temp_max\":273.05},\"wind\":{\"speed\":1.11,\"deg\":260.506},\"rain\":{\"3h\":0},\"clouds\":{\"all\":44},\"dt\":1413780770,\"id\":6094817,\"name\":\"Ottawa\",\"cod\":200}\n"
最佳答案
JSON 已经是原生 Javascipt 对象,但 weatherData.temp
是 undefined
因为它不是对象的属性之一。你想要的嵌套在 main
下:
weatherData.main.temp // 273.05
既然您提到您是 JS/Node 的新手,那么了解 console.log() 和 util.inspect() 可能会有所帮助。您可以使用这些工具将对象输出到控制台以检查其结构。
关于javascript - 如何将 JSON 的特定部分转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26458866/