GusDev
GusDev

Reputation: 297

parsing JSON on appcelerator

i have a webservice like this:

{"person":{"name account":"Jhon Doe","Image":"image/test","Adress":"New York 43","Recomendations":"40"}}

this is what i'm trying to do, when i print datos i get the whole json but when i try to print just the name or Image i don't get anything

var urll = "example.com/example";
var json;
var xhrr = Ti.Network.createHTTPClient({
    onload: function() {
        json = JSON.parse(this.responseText);
        var datos = JSON.stringify(json);
        var medicos = datos;
        Ti.API.info("Json! "+datos);
}
});
xhrr.open('GET', urll);
xhrr.send();

i tried with datos[0].person, datos.person but nothing

Upvotes: 0

Views: 1188

Answers (2)

John Dalsgaard
John Dalsgaard

Reputation: 2807

You have to understand the difference between a string that contains a JSON representation of an object - and the object itself.

Your json variable contains the object (which is what JSON.parse(...) does - convert a text string to an object). On the object you can refer to the attributes as you discovered. You can do this in two ways:

json.person.Address
json.person['name account']

I would suggest that you try to avoid attributes with names that are not valid identifiers (as the latter of the two) as this makes it a little more difficult to use them - e.g. by not allowing the dot notation.

Your datos variable on the other hand contains the string representation of the json object (as JSON.stringify(...) does exactly that - convert an object to its string representation). This means that datos is the same as this.responseText (since you first parse it and then stringify it back).

So JSON.stringify(...) is a brilliant way to make the object "human readable" but you need the object to work with the data.

Hope this clarifies the terms a little ;-)

/John

Upvotes: 6

GusDev
GusDev

Reputation: 297

i just find the solution:

Ti.API.info("Json! "+json.person.Recomendations);

Upvotes: 1

Related Questions