James
James

Reputation: 43617

jQuery json decode

$.getJSON(
    "test.php",
    function(data){
        ... code should be here?
    }
)

data contains this code:

{
    "name": "Mary",
    "surname": "Carey"
}

I want to create these variables:

theName = name from json;
theSurname = surname from json;

What is a true syntax for this task?

Thanks.

Upvotes: 4

Views: 7558

Answers (3)

2-bits
2-bits

Reputation: 473

The "data" should be a Javascript Object. If that is truly the data, you should be able to access it with data['name'] and data['surname'].

'dot' syntax should also work. (i.e. data.name and data.surname)

Upvotes: 0

karim79
karim79

Reputation: 342625

Dot notation:

theName = data.name;
theSurname = data.surname;

or square-bracket notation:

theName = data['name'];
theSurname = data['surname'];

Upvotes: 3

Quentin
Quentin

Reputation: 943142

You could do:

theName = data.name
theSurname = data.surname

… but it is probably better to keep them nicely wrapped up in data and just use that.

Upvotes: 2

Related Questions