如何从JS中获取JSON的值(How to get the value from JSON in JS)

编程入门 行业动态 更新时间:2024-10-15 00:23:23
如何从JS中获取JSON的值(How to get the value from JSON in JS)

我正在尝试从此JSON文件中获取“formatted_address”值。 我是新手,发现文档很混乱。 我现在的代码如下,其中变量“location”是如上所述生成的url。

$.getJSON(location, function( data ){ stad = data.results.formatted_address; console.log(stad); });

我怎么做到这一点?

I'm trying to get the "formatted_address" value from this JSON file. I'm new to this and found the documentation quite confusing. The code I have now is the following where the variable "location" is the url generated like the one above.

$.getJSON(location, function( data ){ stad = data.results.formatted_address; console.log(stad); });

How would I achieve this?

最满意答案

results是一个数组,因此您需要将其作为一个数组进行访问。 鉴于您的示例只有一个项目,您可以通过索引直接访问它:

var stad = data.results[0].formatted_address; // = "'s-Hertogenbosch, Netherlands"

如果数组中有多个项目,则需要循环遍历它们:

for (var i = 0; i < data.results.length; i++) { var stad = data.results[i].formatted_address; // do something with the value for each iteration here... }

results is an array, so you need to access it as one. Given your example with only one item, you can access it directly by index:

var stad = data.results[0].formatted_address; // = "'s-Hertogenbosch, Netherlands"

If there were multiple items in the array you would need to loop through them:

for (var i = 0; i < data.results.length; i++) { var stad = data.results[i].formatted_address; // do something with the value for each iteration here... }

更多推荐

本文发布于:2023-07-07 21:27:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1068442.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:JS   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!