Reputation: 105
I have a string like below
"{stockName: NSE:APOLLOTYRE, stockSignal: Buy, triggerPrice: 204.25, triggerDate: 44900}"
Now how can I convert this to json as below:
{
stockName: APOLLOTYRE,
stockSignal: Buy,
triggerPrice: 204.25,
triggerDate: 44900
}
Please note that "NSE:" should be deleted from resulting JSON I tried below code but obviously it not working.
var data_array = input.body.split(',');
var json = JSON.stringify(data_array);
console.log(json);
Upvotes: 1
Views: 673
Reputation: 20236
You can use String.replace to add quotes to the properties in your pseudo-JSON to convert it to proper JSON, then use JSON.parse:
var input = "{stockName: NSE:APOLLOTYRE, stockSignal: Buy, triggerPrice: 204.25, triggerDate: 44900}";
var withQuotes = input.replace(/(\b[a-z]+:)?(\b[a-z]+\b)/gi, '"$2"');
var parsed = JSON.parse(withQuotes);
console.log(parsed);
Upvotes: 3
Reputation: 125
For transorm your string into JSON object you have to make this:
var s = "{stockName: APOLLOTYRE, stockSignal: Buy, triggerPrice: 204.25, triggerDate: 44900}"
like this:
var s = "{\"stockName\": \"APOLLOTYRE\", \"stockSignal\": \"Buy\", \"triggerPrice\": 204.25, \"triggerDate\": 44900}"
and after you can parse it from json to javaScript object with
JSON.parse(s);
You can try something like this:
var s = "{stockName: APOLLOTYRE, stockSignal: Buy, triggerPrice: 204.25, triggerDate: 44900}";
s = s.replace(/{/g, '{\"');
s = s.replace(/}/g, '\"}');
s = s.replace(":", '\":\"');
s = s.replace(/, /g, '\",\"');
JSON.parse(s);
Upvotes: 1