Home > OS >  Teleport API: Access JSON Object properties
Teleport API: Access JSON Object properties

Time:10-19

I am learning some things about API calls in Javascript. For this, I make a call to the teleport api.

From there I get an Json object back. Now I would like to access the link which you can see in the "json object" below.

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

I have a problem with the "city:search-results" key, because I cant use a the ":" in the dotted notation.

so, how can I get the href value?

I hope its understandable, im sorry for the bad explanation. Thanks for your help!

CodePudding user response:

I see how the JSON is returned. For this example, use bracket notation for city:search-results as

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

And for accessing the href property:

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

Example code (with 2 city:search-results objects):

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"]);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related