繁体   English   中英

将字符串格式错误的json转换为json对象

[英]Converting a badly stringfied json to a json object

我有一些要从Web服务中提取的数据。 这是字符串

(正文:“ 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序列化对象,contentEncoding = null,contentLength = 0,deliveryMode = null,receivedDeliveryMode = PERSISTENT,到期时间= null,优先级= 0,重新交付= false,receivedExchange =,receivedRoutingKey = bottomlesspit, receiveDelay = 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的值?

使用此正则表达式代替匹配的Body

\bBody:'(\d*)'

这将捕获组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')); 

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

例:

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
}

暂无
暂无

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

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