Gendaful
Gendaful

Reputation: 5802

how to parse below simple json response?

BackGround : I am trying to parse this simple json response in my SenchaTouch Application.

json response:

{
    "Australia": 
    [
        {
            "Currency": "AustralianDollar",
        }
    ],
    "INDIA": 
    [
        {
            "Currency": "INR"
        }
    ],
    "USA": 
    [
        {
            "Currency": "USD"
        }
    ]
}

I want to fetch country's currency based on the Country name.

I am trying to fetch the currency value as below.

var country = text.Australia.name;
console.log('Country name is'+country);

but it gives me error. Can any one please explain on how to parse give country name as input and fetch the currency?

Thank you, Gendaful

Upvotes: 2

Views: 252

Answers (5)

Matti Mehtonen
Matti Mehtonen

Reputation: 1705

Best way to do this if by using JSON.parse(). All browsers does not support this but you can get fallback by using Douglas Crockford implementations at https://github.com/douglascrockford/JSON-js

Upvotes: 0

Andrea Cammarata
Andrea Cammarata

Reputation: 836

In Sencha Touch you should use

var object = Ext.decode(text);

to convert a json string into an Object. Then, in your case, since "Australia" in not an object but an array, you need to get the first element currency by

object.Australia[0].Currency;

Upvotes: 2

Guillermo Bergengruen
Guillermo Bergengruen

Reputation: 123

You can use jQuery's $.parseJSON()

After that you can use:


    var text = $.parseJSON(jsonString);
    var currency = text.Australia[0].Currency;

Being the jsonString, the one you obtain via JSON.

Hope this helps!

Upvotes: -2

Paul Fleming
Paul Fleming

Reputation: 24526

The simplest way to do it is:

var obj = eval("(" + text+ ')');

Check out json.org for better/safer ways to do it.

Working example here.

Check out this compatibility chart for using JSON.parse(text);.

Upvotes: 1

Mike Brant
Mike Brant

Reputation: 71422

If text is the JSON string you can do this:

var obj = JSON.parse(text);
var australia = obj.Australia;
var aussie_currency = australia[0].Currency;

Note that the odd nesting of the object containing Currency inside of an array causes the need for the array index reference [0].

Upvotes: 3

Related Questions