将严重字符串化的json转换为json对象

时间:2018-05-21 09:33:52

标签: javascript json

我从网络服务中获取了一些数据。这是字符串

  

(正文:' 3886' MessageProperties [headers = {},timestamp = null,   messageId = null,userId = null,receivedUserId = null,appId = null,   clusterId = null,type = null,correlationId = null,   correlationIdString = null,replyTo = null,   的contentType =应用程序/ x-java的序列化对象,   contentEncoding = null,contentLength = 0,deliveryMode = null,   receivedDeliveryMode = PERSISTENT,expiration = null,priority = 0,   redelivered = false,receivedExchange =,   receivedRoutingKey = bottomlesspit,receivedDelay = null,deliveryTag = 62,   messageCount = 0,consumerTag = amq.ctag-sCwfLaMEqWp2GkFwFrY1yg,   consumerQueue = bottomlesspit])

它看起来像json,但键值对几乎没问题,但最重要的键是Body并不像字符串所说的其他键。

我需要阅读Body的值,并且能够获得像这样的值

   console.log(d.body);
   //This above outputs the string as shown
   obj = eval('{' + d.body + '}');
   console.log(obj);
   var match = "Body";
   var val = obj.find( function(item) { return item.key == match } );
   console.log(val);

如何读取密钥Body的值?

3 个答案:

答案 0 :(得分:1)

使用此正则表达式而不是匹配Body

\bBody:'(\d*)'

这将捕获组1中的Body编号。

答案 1 :(得分:1)

您可以编写解析器函数获取字符串并提取值。这里有一个非常简单的功能。您也可以修改所有例外情况。



var str = `(Body:'3886' MessageProperties [headers={}, timestamp=null, messageId=null, userId=null, receivedUserId=null, appId=null, clusterId=null, type=null, correlationId=null, correlationIdString=null, replyTo=null, contentType=application/x-java-serialized-object, contentEncoding=null, contentLength=0, deliveryMode=null, receivedDeliveryMode=PERSISTENT, expiration=null, priority=0, redelivered=false, receivedExchange=, receivedRoutingKey=bottomlesspit, receivedDelay=null, deliveryTag=62, messageCount=0, consumerTag=amq.ctag-sCwfLaMEqWp2GkFwFrY1yg, consumerQueue=bottomlesspit])`;

function f(inp) {
  var index = str.indexOf(inp),
       endIndex;
  for(var i = index; i < str.length; i ++) {
    if(str[i] == ',') {
      endIndex = i;
      break;
    }
  }
  var output = str.substr(index, endIndex).split('=');
  return output;
}

console.log(f('consumerQueue'));
&#13;
&#13;
&#13;

答案 2 :(得分:1)

为什么不使用正则表达式来匹配和提取Body。

示例:

const match = d.body.match(/Body:\'(.+)\'/)
if (match) {
  const body = match[1] // This is the value of Body
} else {
   // Unable to find Body, handle it here
}