Reputation: 3347
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!
Upvotes: 0
Views: 1357
Reputation: 20494
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);
Upvotes: 1