【问题标题】:Teleport API: Access JSON Object propertiesTeleport API:访问 JSON 对象属性
【发布时间】:2021-12-05 17:02:51
【问题描述】:

我正在学习一些关于 Javascript 中的 API 调用的知识。为此,我调用了 Teleport api。

从那里我得到一个 Json 对象。现在我想访问您可以在下面的“json object”中看到的链接。

_embedded
    city:search-results     [25]
    0
    _links
    city:item
    href:   https://api.teleport.org/api/cities/geonameid:2661552/
    

我的“city:search-results”键有问题,因为我不能在点分符号中使用“:”。

那么,我怎样才能得到 href 值呢?

我希望它可以理解,我很抱歉解释不好。感谢您的帮助!

【问题讨论】:

  • 你试过什么?如果您收到 JSON 数据,您应该能够使用 dot notationbracket notation 访问数据的属性,就像它是 JavaScript 对象一样。见Object literal notation vs JSON
  • @phentnil 我尝试使用 "_embedded.city:search-results[0]" 来获取第一个条目,但 ":" 出错了。
  • @phentnil 我设法用括号符号做到了,非常感谢!

标签: javascript json api


【解决方案1】:

我看到了 JSON 是如何返回的。对于this example,使用bracket notation 作为city:search-results

_embedded["city:search-results"][0]

对于访问href 属性:

_embedded["city:search-results"][0]["_links"]["city:item"]["href"]

示例代码(带有 2 个city:search-results 对象):

var _embedded = {
  "city:search-results": [{
      "_links": {
        "city:item": {
          "href": "https://api.teleport.org/api/cities/geonameid:1796236/"
        }
      },
      "matching_alternate_names": [],
      "matching_full_name": "Shanghai, Shanghai, China"
    },
    {
      "_links": {
        "city:item": {
          "href": "https://api.teleport.org/api/cities/geonameid:745044/"
        }
      },
      "matching_alternate_names": [],
      "matching_full_name": "Istanbul, Istanbul, Turkey"
    }
  ]
};
console.log(_embedded["city:search-results"][0]["_links"]["city:item"]["href"]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 2011-11-05
    • 2016-04-07
    相关资源
    最近更新 更多