简体   繁体   English

在节点js中将字符串转换为JSON?

[英]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. 我正在使用节点js中的Web服务,它以这种奇怪的格式返回了响应。 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. 我必须通过传递键名称来提取某些值,并且我想将响应转换为JSON以简化解析。 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. 我想提取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". 达里奥的答案基本上可以解决问题,但是值得一提的是,Node的querystring模块可以“免费”完成这种工作。

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 : 您可以使用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) . 您可以对其进行操作,删除或提取值,最后使用JSON.stringify(obj)在JSON中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. 注意 :正如Oleg V. Volkov所评论的那样,如果源字符串包含键或值中的分号(';'和'='),则它将不起作用。

If the returned pattern is constant, it can be achieved using regexp: 如果返回的模式是恒定的,则可以使用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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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