0

i know there are multiple similar topics, however trying their solutions doesn't give me expected result.

Input json string

data:"{"message": "{\"type\":\"CONTROL\",\"command\":\"REQUEST_STATUS_ALL\"}"}"

object declaration/parse:

const msg: Message = <Message>JSON.parse(data.data);

output:

{message: "{"type":"CONTROL","command":"REQUEST_STATUS_ALL"}"}

-values are not properly assigned, but instead in a text form.

the same object looks like this if it's initialized manually(in TS):

Message {type: "CONTROL", status: undefined, command: "REQUEST_STATUS_ALL", body: undefined}

What is the correct way to parse that json string into the Message object?

Thank you!

1

1 Answer 1

1

It seems the value for message was improperly encoded as a string. Calling JSON.parse a second time on the message property will get the result you want, though you might want to fix the underlying cause of the improperly encoded data instead.

parseMessage(data: string) {
   const msgTemp = JSON.parse(data);
   msgTemp.message = JSON.parse(msgTemp.message);
   return <Message>msgTemp;
}

const msg = parseMessage(data.data);
Sign up to request clarification or add additional context in comments.

Comments

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.