station station - 4 months ago 9
jQuery Question

Get comma separated string from array

I have the following JSON in JS.

{
"url":"http://example.com/main.aspx",
"report_template_id":"1",
"interval_secs":"86400",
"analysis_type":"lite",
"email":"rokumar@example.com",
"alerts":["num_domains", "med_load_time", "avg_load_time", "tot_req"]
}


I want the list of alerts to be removed and replaced with comma separated values as follows.

{
"url":"http://example.com/main.aspx",
"report_template_id":"1",
"interval_secs":"86400",
"analysis_type":"lite",
"email":"rokumar@example.com",
"alerts":"num_domains,med_load_time,avg_load_time,tot_req"
}

Answer

Just adding all the steps:-

1). Taking your JSON in a variable.

data = {"url":"http://example.com/main.aspx","report_template_id":"1","interval_secs":"86400","analysis_type":"lite","email":"rokumar@example.com","alerts":["num_domains","med_load_time","avg_load_time","tot_req"]};

2). Parse JSON data to object. Assuming the JSON is a string initially do a typeof(data) to be clear.

data = JSON.parse(data);

3) Change list of alerts to comma separated values

data.alerts = data.alerts.join(',');

4) Convert back to string

data = JSON.stringify(data)

So data will look like

{
    "url": "http://example.com/main.aspx",
    "report_template_id": "1",
    "interval_secs": "86400",
    "analysis_type": "lite",
    "email": "rokumar@example.com",
    "alerts": "num_domains,med_load_time,avg_load_time,tot_req"
}

Note:- If you will just say join() then also it will work, because default delimiter is , only, just to clarify I have given that.

Comments