将数据格式更改为JSON

时间:2015-10-20 04:24:41

标签: javascript c# asp.net json

我想将我的数据更改为所需的 JSON 格式。我的数据如下:

[
  "{
     id:001,
     name:akhilesh,
   }",
  "{
     id:002,
     name:Ram,
   }"
]

我想将上述数据转换为有效的 JSON

[
   {
     "id":"001",
     "name":"akhilesh"
   },
   {
     "id":"002",
     "name":"Ram"
   }
]

我尝试了以下方法,但这些都没有帮助:

  1. JSON.serialize
  2. JSON.parse
  3. eval
  4. 我需要帮助。

    服务器端的确切数据响应是:

    {
        "d": [
            "{id:413,title:ranjan,start:413,end:413}",
            "{id:414,title:raja,start:414,end:414}",
            "{id:415,title:raja g,start:415,end:415}",
            "{id:416,title:abhh,start:416,end:416}",
            "{id:417,title:chta,start:417,end:417}",
            "{id:418,title:Raju,start:418,end:418}",
            "{id:419,title:Ranjan,start:419,end:419}",
            "{id:420,title:Raja,start:420,end:420}",
            "{id:421,title:chitti,start:421,end:421}",
            "{id:422,title:Raja,start:422,end:422}",
            "{id:423,title:raja,start:423,end:423}",
            "{id:424,title:yash,start:424,end:424}",
            "{id:425,title:vsg,start:425,end:425}",
            "{id:431,title:Vimal11,start:431,end:431}",
            "{id:432,title:Aruhi,start:432,end:432}",
            "{id:434,title:Aruhi,start:434,end:434}",
            "{id:435,title:,start:435,end:435}",
            "{id:436,title:xs,start:436,end:436}",
            "{id:437,title:rajkj,start:437,end:437}",
            "{id:438,title:mmt,start:438,end:438}",
            "{id:439,title:xaxa,start:439,end:439}",
            "{id:440,title:yash,start:440,end:440}"
        ]
    }
    

    服务器端代码

    [System.Web.Services.WebMethod]
    public static List<string> getData()
    {
        List<string> data = new List<string>();
    
        using (SqlConnection con = new SqlConnection("Data Source=ACME-PC\\SQL;Integrated Security=true;Initial Catalog=ClinicApplication"))
        {
            SqlCommand cmd = new SqlCommand("select DISTINCT Patient_ID,First_Name,fromtime,totime,Date from tbl_AddPatientInfo", con);
            {
                con.Open();
                SqlDataReader dr = cmd.ExecuteReader();
    
                while (dr.Read())
                {
    
                    string id = "{" +
                        "\"id:\"" + dr["Patient_ID"].ToString() + "," +
                        "title:" + dr["First_Name"].ToString() + "," +
                        "start:" + dr["Patient_ID"].ToString() + "," +
                        "end:" + dr["Patient_ID"].ToString() +
                        "}";
                    string ids = id.Replace(@"""", "");
    
                    data.Add(ids);
                }
                return data;
            }
        }
    }
    

3 个答案:

答案 0 :(得分:14)

如果您已控制从服务器发送响应的方式,我建议使用json_encode(response);如果使用PHP或JSON.stringify(response)使用Javascript(node.js)或其他语言的类似方法。然后在客户端,您可以直接在响应上使用JSON.parse(response)来获取JSON对象。

数组的元素需要用引号括起来,以便可以使用JSON.parse将其转换为JSON。然后map可以与JSON.parse一起使用。

&#13;
&#13;
var arr = [
    '{"id":"001","name":"akhilesh"}',
    '{"id":"002","name":"Ram"}'
];

arr = arr.map(JSON.parse);

console.log(arr);
document.getElementById('result').innerHTML = JSON.stringify(arr, 0, 4);
&#13;
<pre id="result"></pre>
&#13;
&#13;
&#13;

如果您在字符串中没有引号,则可以使用正则表达式添加它们并使其适合传递给JSON.parse

Demo

&#13;
&#13;
var arr = [
    "{id:001,name:akhilesh}",
    "{id:002,name:Ram}"
];

arr = arr.map(function(e) {
    // Add quotes on every alphanumeric character
    return JSON.parse(e.replace(/(\w+)/g, '"$1"'));
});

console.log(arr);
document.getElementById('result').innerHTML = JSON.stringify(arr, 0, 4);
&#13;
<pre id="result"></pre>
&#13;
&#13;
&#13;

答案 1 :(得分:5)

使用regex而不是复杂的javascript(在某些情况下可能无效)。更好地进行服务器端更改以正确获取JSON数据。

  

避免通过字符串连接构建JSON,因为当字符串包含JSON中的某些特殊字符时,您可能会发送损坏的数据。这应该使用JSON序列化程序完成。

[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string getData(){
   List<Dictionary<string, string>> data = new List<Dictionary<string, string>>();
   Dictionary<string, string> item;
   using (SqlConnection con = new SqlConnection("Data Source=ACME-PC\\SQL;Integrated Security=true;Initial Catalog=ClinicApplication"))
   {
       SqlCommand cmd = new SqlCommand("select DISTINCT Patient_ID,First_Name,fromtime,totime,Date from tbl_AddPatientInfo", con);
       {
           con.Open();
           SqlDataReader dr = cmd.ExecuteReader();

           while (dr.Read())
           {
                item = new Dictionary<string, string>();
                item.Add("id", dr["Patient_ID"]+"");
                item.Add("title", dr["First_Name"]+"");
                item.Add("start", dr["Patient_ID"]+"");
                item.Add("end", dr["Patient_ID"]+"");
                data.Add(item);
           }
           return new JavaScriptSerializer().Serialize(data);
       }
    }
}

修改现有代码:

[System.Web.Services.WebMethod]
public static List<string> getData(){
    List<string> data = new List<string>();
    using (SqlConnection con = new SqlConnection("Data Source=ACME-PC\\SQL;Integrated Security=true;Initial Catalog=ClinicApplication"))
    {
       SqlCommand cmd = new SqlCommand("select DISTINCT Patient_ID,First_Name,fromtime,totime,Date from tbl_AddPatientInfo", con);
       {
           con.Open();
           SqlDataReader dr = cmd.ExecuteReader();

           while (dr.Read())
           {
                string id = "{" +
                   "\"id\":"  + "\""+dr["Patient_ID"].ToString()+"\"" + "," +
                   "\"title\":" + "\""+dr["First_Name"].ToString()"\"" + "," +
                   "\"start\":" + "\""+dr["Patient_ID"].ToString()"\"" + "," +
                   "\"end\":" + "\""+dr["Patient_ID"].ToString() + "\""+
                   "}";
                data.Add(id);
           }
           return data;
       }
    }
}

答案 2 :(得分:4)

通过JavaScript修复JSON是错误的。使用字符串函数在服务器端生成JSON同样是垃圾。例如,当数据包含",新行和不包含的行时,您的代码将会中断。

我宁愿使用一些生成JSON的库。以下是使用JavaScriptSerializer的完整示例。它可以转换各种对象。在这里,我们使用ListDictionary个对象:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;

[WebService]
[ScriptService]

public class WebService1 : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string getData()
    {
        List<Dictionary<string, object>> data = new List<Dictionary<string, object>>();
        using (SqlConnection con = new SqlConnection("Data Source=ACME-PC\\SQL;Integrated Security=true;Initial Catalog=ClinicApplication"))
        {
            SqlCommand cmd = new SqlCommand("select DISTINCT Patient_ID,First_Name,fromtime,totime,Date from tbl_AddPatientInfo", con);
            {
                con.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    Dictionary<string, object> item = new Dictionary<string, object>();
                    item.Add("id", dr["Patient_ID"]);
                    item.Add("title", dr["First_Name"]);
                    item.Add("start", dr["Patient_ID"]);
                    item.Add("end", dr["Patient_ID"]);
                    data.Add(item);
                }
            }
        }
        return new JavaScriptSerializer().Serialize(data);
    }
}

使用jQuery进行测试:

jQuery.ajax({
    url: "/testing/WebService1.asmx/getData",
    method: "POST",
    contentType: "application/json",
    dataType: "json",
    success: function (json) {
        var data = jQuery.parseJSON(json.d);
        console.log(data);
    }
});

控制台日志:

[{
    "id": 413,
    "title": "ranjan",
    "start": 413,
    "end": 413
}, {
    "id": 414,
    "title": "raja",
    "start": 414,
    "end": 414
}]