简体   繁体   中英

Converting a string to JSON in node js?

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.

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': '*****' }

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM