1

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}"
3
  • you could try var data = e.data.match(/{[^}]*}/)[0]; Commented Dec 4, 2020 at 20:14
  • thank you very much, this worked. but it leads to the next question :) . Commented Dec 4, 2020 at 20:21
  • how can I extract the individual attribultes, e.g. I want to get only the physicalPath attribute, do you have an idea about how to get? Commented Dec 4, 2020 at 20:22

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

this returns :1 Uncaught SyntaxError: Unexpected token u in JSON at position 0
maybe because the JSON is not a valid JSON?
@Fadi Yeah, try the alernative version (I just updated my answer).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.