javascript - 如何将 JSON 的特定部分转换为字符串?

标签 javascript json node.js

我是 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.tempundefined 因为它不是对象的属性之一。你想要的嵌套在 main 下:

weatherData.main.temp // 273.05

既然您提到您是 JS/Node 的新手,那么了解 console.log() 和 util.inspect() 可能会有所帮助。您可以使用这些工具将对象输出到控制台以检查其结构。

关于javascript - 如何将 JSON 的特定部分转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26458866/

相关文章:

python - 字节串怎样才能很好的存储呢? - 不可 JSON 序列化 -

node.js - 如何使用 Gulp 通过 Browerify 从 Bower 组件创建一个单独的供应商包

javascript - 服务器端处理还是客户端处理?

javascript - jQuery 中的链接替换了 HTML 不起作用

javascript - 在 Kendo UI Treeview 项目旁边添加图像不起作用

javascript - 数据未存储在 Mongodb 中

javascript - 如何为 node.js 创建 native 模块

javascript - 这个函数有内存泄漏吗?

c# - 在 C#、WP7 中将对象转换为 JSON 字符串

json - 解析json时由于输入结束而没有要映射的内容