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

How to get a specific section of JSON into a string?

本文关键字:转换 字符串 定部 JSON      更新时间:2023-09-26

我是JSON、node.js和javascript的新手。。。我有一个小的node.js服务器,它从openweathermap.org获取一个JSON对象(下面名为weatherData),我试图让它只显示JSON对象的特定部分(一个名为"temp"的部分)。到目前为止,我使用了:

var tempString = JSON.stringify(weatherData);

然后我使用字符串的搜索和子字符串方法来获取信息,但肯定有一种更简单的方法,对吧?如何在不使用字符串方法的情况下仅显示temp部分?

编辑:当我把整个东西串起来的时候,我得到了这个

"{''"coord''":{''"lon''":-75.7,''"lat''":45.41},''"sys''":"type''":3,''"id''":119304,''"message''":0.0297,''"country''":''"CA''",''"sunrise''":1413804390,''"日落''":1413842906},"weather ''":[{''clouds''",''"icon''":''"03n''"}],''"base''":''"cmcstations",''"main''":{''"temp''":273.05,''"湿度''":84,''"压力''":1012.188,''"temp_min''":273.05,''"temp_max''":273.05},''"wind''":"速度''":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()可能会有所帮助。您可以使用这些工具将对象输出到控制台以检查其结构。

它已经是JSON格式的,不需要将其转换为字符串。

您可以使用weatherData.temp 直接访问"temp"部分

你试过了吗?

var result = JSON.stringify(weatherData.temp);