最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Change the format of the Data into JSON - Stack Overflow

programmeradmin6浏览0评论

I want to change my data into desired JSON format. My data looks like this:

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

I want to convert the above data to valid 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;
        }
    }
}

I want to change my data into desired JSON format. My data looks like this:

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

I want to convert the above data to valid 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;
        }
    }
}
Share Improve this question edited May 12, 2016 at 12:58 YvesLeBorg 9,0798 gold badges37 silver badges49 bronze badges asked Oct 20, 2015 at 4:24 Akhilesh SinghAkhilesh Singh 1,7242 gold badges19 silver badges35 bronze badges 19
  • 8 why can't you return proper json from server itself ? – Susheel Singh Commented Oct 20, 2015 at 4:33
  • 6 There is only one proper way to solve problems of incorrect data formats - stop using them. It is like "my web-server returns text in French and with many typos; I want it to be displayed in proper English". – Yeldar Kurmangaliyev Commented Oct 20, 2015 at 4:36
  • 8 Fix the server side code to emit valid JSON. Do not attempt to fix broken JSON in JavaScript. – Salman Arshad Commented Oct 20, 2015 at 4:49
  • 3 @AkhileshSingh You should change the server to return valid JSON, now the data is not consistent. title contains space for 415 and it is not present for 435, if changing data format to JSON is not possible, at least make the data consistent – Tushar Commented Oct 20, 2015 at 5:01
  • 3 If that server is under control of your country, then you need to tell your manager that the server team is producing broken JSON. It's quite clear that they intend to produce JSON but are just failing miserably. That's gross incompetence. – gnasher729 Commented Oct 20, 2015 at 6:21
 |  Show 14 more comments

3 Answers 3

Reset to default 13

If you've control on how the response is sent from the server, I'd recommend to use json_encode(response); if using PHP or JSON.stringify(response) if using Javascript(node.js) or similar method for other languages. And then on client-side, you can use JSON.parse(response) directly on the response to get JSON object.

The elements of array need to be wrapped in quotes, so that it can be converted to JSON using JSON.parse. Then map can be used with 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.

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. Its better to do server side changes to get JSON data correctly.

Avoid building the JSON by string concatenation, since you risk sending broken data when the string contains certain special characters in JSON. This should be done with JSON serializer.

[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. Using string functions to generate JSON on server side is equally rubbish. Your code will break for example when the data contains ", new lines and what not.

I would rather use some library that generates JSON. Here is a complete example that uses JavaScriptSerializer. It can convert various objects. Here we use a List of Dictionary objects:

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.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
}]
发布评论

评论列表(0)

  1. 暂无评论