3

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;
        }
    }
}
YvesLeBorg
  • 9,070
  • 8
  • 35
  • 48
Akhilesh Singh
  • 1,724
  • 2
  • 19
  • 35
  • 8
    why can't you return proper json from server itself ? – Susheel Singh Oct 20 '15 at 04:33
  • Because i used list to return this , In list the data itself coming dynamically itself – Akhilesh Singh Oct 20 '15 at 04:35
  • 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 Oct 20 '15 at 04:36
  • Change `},]` to `}]` and `,}` to `}`. The extra commas suggests another item in the arrays. . For example, you want to keep the comma between `}{`. – Victor Stoddard Oct 20 '15 at 04:37
  • 1
    @AkhileshSingh Please add the data exactly as you're getting in the response, no need of formatting it here as it'll invalidate the string. – Tushar Oct 20 '15 at 04:39
  • @AkhileshSingh are you talking about `List` in java ? – Susheel Singh Oct 20 '15 at 04:46
  • List in C sharp @Susheel Singh – Akhilesh Singh Oct 20 '15 at 04:48
  • 8
    Fix the server side code to emit **valid** JSON. Do not attempt to fix broken JSON in JavaScript. – Salman A Oct 20 '15 at 04:49
  • @Tushar i update the Code please lets a look. – Akhilesh Singh Oct 20 '15 at 04:56
  • @AkhileshSingh Can you change the server side API to return JSON encoded data? – Tushar Oct 20 '15 at 04:57
  • i tried sir but its not changing , so i thought i can change it to client side, It is possible or not sir. – Akhilesh Singh Oct 20 '15 at 04:58
  • 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 Oct 20 '15 at 05:01
  • please post your `c#` code lets see if we can help you better – Susheel Singh Oct 20 '15 at 05:03
  • @AkhileshSingh See [How to return JSon object](http://stackoverflow.com/questions/16441880/how-to-return-json-object) and [How can My Asp.Net C# class return a json format](http://stackoverflow.com/questions/5300855/how-can-my-asp-net-c-sharp-class-return-a-json-format). Try `return new JavaScriptSerializer().Serialize(new data);` after including `using System.Web.Script.Serialization` – Tushar Oct 20 '15 at 05:08
  • 2
    @Tushar i already go through to this link but its not working in my case, I tried again. After that i say to you sir and thanx for you precious time Sir. – Akhilesh Singh Oct 20 '15 at 05:16
  • 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 Oct 20 '15 at 06:21
  • 2
    @SalmanA: It's actually valid JSON (as far as I can see), just quite useless: It's an array in a dictionary, containing strings. Just the strings don't contain text, but something that seems to look a little bit like JSON. I've seen people sending strings containing _actual_ JSON (or XML, or HTML) which is enough of a pain, but this isn't. – gnasher729 Oct 20 '15 at 06:23
  • 2
    @gnasher729 let me rephrase then: tweak the server side script to send useful JSON. Is that better? – Salman A Oct 20 '15 at 06:30
  • 1
    17 upvotes to do this guy's job for him!? Some day, you will go to a doctor's office and they will be running the code that this guy is asking for on Stack Overflow. Don't be an enabler. – Mark E. Haase Oct 20 '15 at 15:37

3 Answers3

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>
Tushar
  • 85,780
  • 21
  • 159
  • 179
5

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;
       }
    }
}
Susheel Singh
  • 3,824
  • 5
  • 31
  • 66
4

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
}]
Salman A
  • 262,204
  • 82
  • 430
  • 521
  • Sir you assign the value statically but my data is coming from database and then add to the list. How it can be done? – Akhilesh Singh Oct 20 '15 at 08:58
  • 2
    It is just for illustration. See Susheel's revised answer who borrowed code from my example to create complete example using data reader. – Salman A Oct 20 '15 at 09:01