Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery how to deserialize json object [duplicate]

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;
}
like image 791
Arif YILMAZ Avatar asked Apr 04 '13 14:04

Arif YILMAZ


4 Answers

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

like image 158
Alex Avatar answered Nov 13 '22 20:11

Alex


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);
      });
}
like image 37
kimpettersen Avatar answered Nov 13 '22 20:11

kimpettersen


If you really want to use jQuery, here is the function However, any contemporal browser has function

JSON.parse()
like image 2
Tommi Avatar answered Nov 13 '22 21:11

Tommi


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.

like image 1
Blazemonger Avatar answered Nov 13 '22 22:11

Blazemonger