简体   繁体   English

将数据格式更改为JSON

[英]Change the format of the Data into JSON

I want to change my data into desired JSON format. 我想将我的数据更改为所需的JSON格式。 My data looks like this: 我的数据如下:

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

I want to convert the above data to valid JSON : 我想将上述数据转换为有效的JSON

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

I tried the following, but none of these helped: 我尝试了以下方法,但这些都没有帮助:

  1. JSON.serialize
  2. JSON.parse
  3. eval

I need help for this. 我需要帮助。

The exact data response from server side is: 服务器端的确切数据响应是:

{
    "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}"
    ]
}

Server Side Code 服务器端代码

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

If you've control on how the response is sent from the server, I'd recommend to use json_encode(response); 如果您已经控制了如何从服务器发送响应,我建议使用json_encode(response); if using PHP or JSON.stringify(response) if using Javascript(node.js) or similar method for other languages. 如果使用PHP或JSON.stringify(response)如果使用Javascript(node.js)或其他语言的类似方法。 And then on client-side, you can use JSON.parse(response) directly on the response to get JSON object. 然后在客户端,您可以直接在响应上使用JSON.parse(response)来获取JSON对象。

The elements of array need to be wrapped in quotes, so that it can be converted to JSON using JSON.parse . 数组的元素需要用引号括起来,以便可以使用JSON.parse将其转换为JSON。 Then map can be used with JSON.parse. 然后map可以与JSON.parse一起使用。

 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); 
 <pre id="result"></pre> 


If you don't have quotes in the string, you can use regex to add them and make it suitable to pass to JSON.parse . 如果字符串中没有引号,则可以使用正则表达式添加它们并使其适合传递给JSON.parse

Demo 演示

 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); 
 <pre id="result"></pre> 

Instead of doing a complex regex (which is might not work in some conditions) by using javascript . 而不是使用javascript执行复杂的regex (在某些条件下可能不起作用)。 Its better to do server side changes to get JSON data correctly. 更好地进行服务器端更改以正确获取JSON数据。

Avoid building the JSON by string concatenation, since you risk sending broken data when the string contains certain special characters in JSON. 避免通过字符串连接构建JSON,因为当字符串包含JSON中的某些特殊字符时,您可能会发送损坏的数据。 This should be done with JSON serializer. 这应该使用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);
       }
    }
}

modification to your existing code: 修改现有代码:

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

Fixing JSON via JavaScript is wrong. 通过JavaScript修复JSON是错误的。 Using string functions to generate JSON on server side is equally rubbish. 使用字符串函数在服务器端生成JSON同样是垃圾。 Your code will break for example when the data contains " , new lines and what not. 例如,当数据包含" ,新行和什么不包含" ,您的代码将会中断。

I would rather use some library that generates JSON. 我宁愿使用一些生成JSON的库。 Here is a complete example that uses JavaScriptSerializer . 这是一个使用JavaScriptSerializer的完整示例。 It can convert various objects. 它可以转换各种对象。 Here we use a List of Dictionary objects: 这里我们使用List of Dictionary对象:

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

Testing with jQuery: 使用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);
    }
});

Console Log: 控制台日志:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM