将数据格式转换为JSON

3

我想把我的数据转换成所需的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;
        }
    }
}

8
为什么服务器本身不能返回正确的JSON格式? - Susheel Singh
6
解决数据格式不正确的问题只有一种正确的方法 - 停止使用它们。这就像“我的 Web 服务器返回法语文本,并且有很多错别字;我希望它显示为正确的英语”一样。 - Yeldar Kurmangaliyev
8
请修复服务器端代码以发出有效的 JSON。不要尝试在 JavaScript 中修复损坏的 JSON。 - Salman A
3
你应该将服务器更改为返回有效的JSON,现在数据不一致。title 对于415包含空格,而对于435则不存在。如果无法更改数据格式为JSON,则至少使数据保持一致。 - Tushar
3
如果那个服务器在你们国家的控制下,那么你需要告诉你的经理服务器团队正在生成错误的JSON。很明显他们本意是要生成JSON但却做得很糟糕。这是极端无能。 - gnasher729
显示剩余14条评论
3个回答

13

如果你掌控着从服务器发送响应的方式,我建议使用 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);
<pre id="result"></pre>

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

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>


2
你清楚地读了他的问题吗?他之前没有双引号,想要在之后加上双引号。 - Susheel Singh
我的数据是动态获取的,它能正常工作吗? - Akhilesh Singh
1
@SusheelSingh 这不是“有效字符串”,这只是在问题中添加格式,当响应从服务器发送时,将不会有空格。 - Tushar
1
是的,但我不太喜欢在客户端调整代码。我认为如果他能够正确返回JSON会更好。所以你的答案现在是正确的。点赞! - Susheel Singh
@Tushar 小提醒,PHP 中是 json_encode,用的是下划线 _,不是点号 . :) - TMH
显示剩余2条评论

5

使用 JavaScript 来进行复杂的正则表达式匹配可能会在某些情况下失败。因此,更好的方法是通过服务器端更改来正确获取 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;
       }
    }
}

刚刚做了一个小修改,请再次检查。 - Susheel Singh
你现在是否得到了正确的响应?如果没有,请发布更新的输出,我会继续帮助你。 - Susheel Singh
避免使用字符串拼接构建JSON,因为当字符串包含某些特殊字符时,您可能会发送损坏的数据。应该使用JSON序列化器来完成这项工作。 - nhahtdh

4
修复 JSON 是通过 JavaScript 的方式是错误的,使用字符串函数在服务器端生成 JSON 同样是不可靠的。例如,当数据包含“"”、“换行符”等特殊字符时,您的代码将会出错。
我更倾向于使用一些库来生成 JSON。下面是一个完整的示例,使用 JavaScriptSerializer。它可以转换各种对象。这里我们使用了一个List字典对象:
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
}]

先生,您是静态分配值,但我的数据来自数据库然后添加到列表中。应该如何操作? - Akhilesh Singh
2
这只是为了说明。请参阅Susheel的修订答案,他从我的示例中借用了代码,以使用数据读取器创建完整的示例。 - Salman A

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接