简体   繁体   中英

I am trying to retrieve data from a JSON file, but I am having trouble retrieving information from a specific property

Here is my JSON file:

{
    "query":{
        "count":1,
        "created":"2016-06-16T21:09:11Z",
        "lang":"en-US",
        "results":{
            "channel":{
                "units":{
                    "distance":"mi",
                    "pressure":"in",
                    "speed":"mph",
                    "temperature":"F"
                },
                "title":"Yahoo! Weather - Ormond Beach, FL, US",
                "link":"http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-2466336/",
                "description":"Yahoo! Weather for Ormond Beach, FL, US",
                "language":"en-us",
                "lastBuildDate":"Thu, 16 Jun 2016 05:09 PM EDT",
                "ttl":"60",
                "location":{
                    "city":"Ormond Beach",
                    "country":"United States",
                    "region":" FL"
                }
            }
        }
    }
}

This is not all of the code, but it is the part that I am having trouble with.

I am trying to save the location ( Ormond Beach, Fl ) as a variable. I am using this angularjs code and it doesn't seem to work: $scope.location = response.data.query.results.location; . There is nothing wrong with the JSON file, as I have retrieved other information much later in the JSON file using ng-repeat , but, I am having trouble saving Ormond Beach as the variable $scope.location . Please help me!

Thanks so much!

response.data.query.results.location is not a string, it is an object that has 3 properties that are each strings:

{
    "city":"Ormond Beach",
    "country":"United States",
    "region":" FL"
}

You need to concatenate the properties you desire:

$scope.location = response.data.query.results.location.city + ', ' + response.data.query.results.location.region;

Just for fun, I'll show you the form I like to use for this sort of thing:

$scope.location = [
    response.data.query.results.location.city,
    response.data.query.results.location.region
].join(', ');

It helps me see very clearly just which pieces of data are making their way in.

There's an intermediate object between location and result which is channel.

Try instead:

$scope.location = response.data.query.results.channel.location;

Then you just need to concatenate location.city and location.region

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM