Reputation: 423
I have following string in c#,
"2015-9-9,2015-9-10,2015-9-11,2015-9-12,2015-9-13,2015-9-14"
now I want to convert that in a javascript variable like following json format.I want to send to server side to client side in one variable and required to use in javascript varialbe.
var avadates = ["2015-9-9", "2015-9-10", "2015-9-11", "2015-9-12", "2015-9-13", "2015-9-14"];
so,How to convert in Json from C# or any otherways to do that?
Upvotes: 0
Views: 171
Reputation: 4017
This gets every date, add then convert it to string adding the 0 to the month, then merge all the dates:
string toJsonify = "2015-9-9,2015-9-10,2015-9-11,2015-9-12,2015-9-13,2015-9-14";
var dates = toJsonify.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)
.Select(s => DateTime.ParseExact(s, "yyyy-M-d", System.Globalization.CultureInfo.InvariantCulture)
.ToString("yyyy-MM-dd"));
var res = "[\"" + string.Join("\",\"", dates) + "\"]";
Upvotes: 2
Reputation: 332
probably not the most elegant way of achieving what you want but using the JSON.net libaray you can get the results in a J array using the following code.
string sample = "2015-9-9,2015-9-10,2015-9-11,2015-9-12,2015-9-13,2015-9-14";
List<string> list = sample.Split(',').ToList<string>();
string json = JsonConvert.SerializeObject(list);
JArray result = JArray.Parse(json);
Upvotes: 0