Fadi
Fadi

Reputation: 203

extract an object from from a JSON response in nodeJs

I am receiving a message from a WebSocket like so

ws.onmessage = (e) => {
       debugger
       if (e.data.startsWith('MESSAGE'))
           alert(JSON.stringify(e.data))
       ImageReceived(e.data)
       console.log(JSON.stringify(e.data))
   }

the message, However, is received correctly, but I am having some difficulties in extracting the content I desire from the message. The message looks as follows, and I want to extract this part from the message :

{"physicalPath":"E:\\NORMAL\\person.jpeg","status":"Normal","version":47,"issuer":"gmail.com","id":32631}

and the message is structured as follows

"MESSAGE
expires:1607105481567
destination:/queue/[email protected]
_type:com.model.Image
priority:9
message-id:ID:LA99343812-1:1:1:1:20
persistent:true
timestamp:1607105445567

{"physicalPath":"E:\\NORMAL\\person.jpeg","status":"Normal","version":47,"issuer":"gmail.com","id":32631}"

Upvotes: 1

Views: 395

Answers (1)

Đinh Carabus
Đinh Carabus

Reputation: 3496

In response to your last comment: You could try to parse the extracted string into an actual object

var data = JSON.parse(e.data.match(/{[^}]*}/)[0]);

alternatively (data is not valid JSON)

var data = new Function("", "return " + e.data.match(/{[^}]*}/)[0])()

then you can access the individual properties like this

data.physicalPath

Upvotes: 1

Related Questions