Adam92
Adam92

Reputation: 436

Deserialising JSON Data

I've an example string being return through a post call to an ASP handler.

alert("Data: " + data);

Is working and alerting the string.

[{"Item1":"stringone","Item2":"stringtwo"}]

I cant seem to be able to access the data in Item1 and Item2 so I can enter it into a textbox?

$('#txtFOA').val(data[0]);
$('#txtAddress').val(data[2]);

Upvotes: 0

Views: 46

Answers (3)

Burak Karakuş
Burak Karakuş

Reputation: 1410

You should first parse that string to JSON like this:

var jsonified = JSON.parse(data);

then you can access its elements like this:

jsonified[0].Item1

Upvotes: 1

SenthilKumarM
SenthilKumarM

Reputation: 119

data[0] returns the entire object

{
  "Item1": "stringone",
  "Item2": "stringtwo"
}

If you want to enter "stringone" in textbox, use something like this

data[0].Item1
or 
data[0]["Item1"]

Also you can't access data[2] in this case, since you have only one element in your result array.

$('#txtFOA').val(data[0].Item1);
$('#txtAddress').val(data[0].Item2);

or 

$('#txtFOA').val(data[0]["Item1"]);
$('#txtAddress').val(data[0]["Item2"]);

Upvotes: 0

Everson Rafael
Everson Rafael

Reputation: 2093

try

$('#txtFOA').val(data[0].Item1);
$('#txtAddress').val(data[2].Item2);

Upvotes: 1

Related Questions