0

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.

1
  • 2
    Split to pairs with .split(';'), then split each pair to k/v with .split('='). This might be harder if values can include ; and =. Commented Mar 28, 2017 at 9:35

3 Answers 3

2

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': '*****' }
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.