Reputation: 127
I am consuming a webservice in node js and it returns me the response in this strange format. I have to extract certain values by passing the key names and I would like to convert the response to a JSON for ease of parsing. How should I go about it ?
This is what I get from the webservice
Data Source=*******;Initial Catalog=****;User ID=*******;Password=
*******;MultipleActiveResultSets=True;Min Pool Size=5;Max Pool Size=5000;Conn
ect Timeout=180;Application Name=*****
I want to extract DataSource , UserID, Password.
Upvotes: 0
Views: 3475
Reputation: 168863
Dario's answer basically does the trick, but it's worth knowing that Node's querystring
module does this sort of stuff "for free".
The code
const qs = require('querystring');
const s = `Data Source=*******;Initial Catalog=****;User ID=*******;Password=*******;MultipleActiveResultSets=True;Min Pool Size=5;Max Pool Size=5000;Connect Timeout=180;Application Name=*****`;
console.log(qs.parse(s, ';', '='));
outputs:
{ 'Data Source': '*******',
'Initial Catalog': '****',
'User ID': '*******',
Password: '*******',
MultipleActiveResultSets: 'True',
'Min Pool Size': '5',
'Max Pool Size': '5000',
'Connect Timeout': '180',
'Application Name': '*****' }
Upvotes: 2
Reputation: 171
If the returned pattern is constant, it can be achieved using regexp:
var result = str.match(/Source=(.*);Initial.*ID=(.*);Password=(.*);Multiple/)
And then take your desired values from matched groups.
DataSource = result[1];
UserId = result[2];
Password = result[3];
Upvotes: 0
Reputation: 4035
You can easily parse it with String split:
const obj = response.split(';', 2).reduce((json, pair) => {
const tokens = pair.split('=', 2);
json[tokens[0]] = tokens[1];
return json;
}, {});
You can manipulate it, deleting or extracting values, and finally encoding it in JSON with JSON.stringify(obj)
.
Note: as Oleg V. Volkov comments, if the source string contains delimeters (';' and '=') in key or value, it will don't work.
Upvotes: 1