【问题标题】:Change the format of the Data into JSON将数据的格式更改为 JSON
【发布时间】:2016-01-18 14:24:56
【问题描述】:

我想将我的数据更改为所需的 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

我需要这方面的帮助。

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

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

【问题讨论】:

  • 为什么不能从服务器本身返回正确的 json?
  • 只有一种正确的方法可以解决数据格式不正确的问题——停止使用它们。这就像“我的网络服务器返回法语文本,并且有很多错别字;我希望它以正确的英语显示”。
  • 修复服务器端代码以发出 有效 JSON。不要尝试修复 JavaScript 中损坏的 JSON。
  • @AkhileshSingh 您应该更改服务器以返回有效的 JSON,现在数据不一致。 title 包含 415 的空间,而 435 不存在,如果无法将数据格式更改为 JSON,至少使数据保持一致
  • 如果该服务器在您所在国家/地区的控制之下,那么您需要告诉您的经理该服务器团队正在生成损坏的 JSON。很明显,他们打算生成 JSON,但只是惨遭失败。这是严重的无能。

标签: javascript c# asp.net json


【解决方案1】:

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

数组的元素需要用引号括起来,以便可以使用JSON.parse 将其转换为JSON。然后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);
&lt;pre id="result"&gt;&lt;/pre&gt;

如果字符串中没有引号,可以使用正则表达式添加它们并使其适合传递给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);
&lt;pre id="result"&gt;&lt;/pre&gt;

【讨论】:

  • 你看清楚他的问题了吗?他之前没有双引号,而后想要双引号。
  • 我的数据是动态的,它应该可以工作吗??
  • @SusheelSingh 那不是有效的字符串,那是有问题的添加时格式化的,从服务器发送响应时不会有空格
  • 希望如此,让 OP 回复准确的数据
  • 是的,但我在客户端修改代码感觉不好。我认为如果他能正确返回json会更好。所以你的答案现在是正确的。点赞
【解决方案2】:

通过使用javascript 而不是执行复杂的regex(在某些情况下可能不起作用)。最好进行服务器端更改以正确获取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;
       }
    }
}

【讨论】:

  • 刚刚又做了一点零钱检查
  • 你现在得到正确的回应了吗?如果没有,请发布更新后的输出,我会进一步帮助您
  • 避免通过字符串连接构建 JSON,因为当字符串包含 JSON 中的某些特殊字符时,您可能会发送损坏的数据。这应该使用 JSON 序列化程序来完成。
【解决方案3】:

通过 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
}]

【讨论】:

  • 先生,您静态分配值,但我的数据来自数据库,然后添加到列表中。怎么做?
  • 仅供说明之用。请参阅 Susheel 的修订答案,他从我的示例中借用代码以使用数据阅读器创建完整示例。
猜你喜欢
  • 2020-04-14
  • 1970-01-01
  • 2014-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-16
  • 2023-03-18
相关资源
最近更新 更多