1
   {
    "data": {
        "weather": [{
            "id": 800,
            "main": "Clear",
            "description": "clear sky",
            "icon": "01d"
        }],
        "id": 1271714,
        "name": "Gandhi Nagar",
        "cod": 200
    },
    "status": 200,
    "config": {
        "method": "GET",
        "transformRequest": [null],
        "transformResponse": [null],
        "url": "http://api.openweathermap.org/data/2.5/weather?lat=13.0414146&lon=80.2599991&appid=016040457f30e1967b4025f18e225136",
        "headers": {
            "Accept": "application/json, text/plain, */*"
        }
    },
    "statusText": "OK"
}

Unable to access the data.name string. The method I use is as follows. The below mentioned method returns an error. I am new to AngularJS, please do help me if I am making any mistake.

var city = angular.fromJson(result.data.name);
4
  • 1
    Could you show your $http call ? Commented May 2, 2016 at 7:06
  • It works fine(Assuming your JSON is being assigned properly)? Plunkr Link Commented May 2, 2016 at 7:08
  • Have you tried result.name directly? Commented May 2, 2016 at 7:12
  • It works for all other data like result.data.cod Commented May 2, 2016 at 7:24

2 Answers 2

1

Try below:

result = angular.fromJson(result);
var city = result.data.name;
Sign up to request clarification or add additional context in comments.

3 Comments

it worked..!! But can you tell me why my method didn't work..??
From what I understand angular.fromJson() requires a JSON input. I assumed that result is the JSON object you got. You would need to convert the whole JSON object first and extract the object property you need, instead of extracting the property first and converting only that part to string. Anyone please correct me if I'm wrong. What I did not understand is why it required fromJson conversion in the first place: simply var city = result.data.name; usually just works for me.
@yclee0210: Your description is correct. Well, the data that has been provided in the question is not really a JSON string. In fact it's a simple object and accessing properties directly should not raise an error. The error may have been caused because he tried to parse a simple string (result.data.name). Parsing a number on the other hand works just fine (result.data.cod). A real JSON string would have the outer {} placed inside another pair of "".
1

Try this. angular.fromJsonneeds an valid json string and result.data.name is not a vaild json string. After deserializeing this string into JSON object you are able to get your value.

var city = angular.fromJson(result).data.name;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.