How can you deserialize this json object below?
[{"id":"67","name":"TestString"}]
I tried to do this below but couldnt succeed...
success: function (data, status) {
$.each(data, function (dt) {
var mydata = data.d;
alert(mydata); // returns [{"id":"67","name":"TestString"}]
$("#txt_speciality").tokenInput("add", mydata.id);
});
}
here is the way I am creating the json object
[WebMethod]
public static string get_specialities(string ProfessionalID)
{
Database db = DatabaseFactory.CreateDatabase("Connection String2");
DbCommand dbCommand;
dbCommand = db.GetStoredProcCommand("Select_Professionals_Speciality");
db.AddInParameter(dbCommand, "prof_id", DbType.Int16, Convert.ToInt16(ProfessionalID));
IDataReader dr = db.ExecuteReader(dbCommand);
//[{ id: 3, name: "test3" }]
string return_str="[";
int i = 0;
while (dr.Read()) {
if (i > 0)
return_str += ",";
return_str += "{\"id\":\"" + dr["SpecialtyID"].ToString().Trim() + "\",\"name\":\"" + dr["SpecialtyName"].ToString().Trim() + "\"}";
i++;
}
return_str += "]";
return return_str;
}
You can do this with:
var mydata; // [{"id":"67","name":"TestString"}]
var json = $.parseJSON(mydata);
the json variable will contain the de-serialized json object
I assume this is what you need: JSON.parse(data)
success: function (data, status) {
data = JSON.parse(data);
$.each(data, function (dt) {
var mydata = data.d;
alert(mydata); // returns [{"id":"67","name":"TestString"}]
$("#txt_speciality").tokenInput("add", mydata.id);
});
}
If you really want to use jQuery, here is the function However, any contemporal browser has function
JSON.parse()
If you're retrieving your data as text, it's not parsed as an array on arrival, but as a string.
Use .getJSON
or datatype:json
in your $.ajax()
options to resolve this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With