jQuery jquery如何反序列化json对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15813823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:50:33  来源:igfitidea点击:

jquery how to deserialize json object

jqueryasp.netjson

提问by Arif YILMAZ

How can you deserialize this json object below?

你如何反序列化下面的这个 json 对象?

[{"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

这是我创建 json 对象的方式

[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;
}

回答by Alex

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

json 变量将包含反序列化的 json 对象

回答by kimpettersen

I assume this is what you need: JSON.parse(data)

我假设这是你需要的: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);
      });
}

回答by Tommi

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

如果你真的想使用 jQuery,这里是功能但是,任何同时代的浏览器都有功能

JSON.parse()

回答by arnoldrob

var object = JSON.parse(data);

Now you cann access all the atributes. For example object.id

现在您可以访问所有属性。例如 object.id

回答by Blazemonger

If you're retrieving your data as text, it's not parsed as an array on arrival, but as a string.

如果您以文本形式检索数据,则不会在到达时将其解析为数组,而是将其解析为字符串。

Use .getJSONor datatype:jsonin your $.ajax()options to resolve this.

使用.getJSONdatatype:json在您的$.ajax()选项中解决此问题。