Web Develop Wolf
Web Develop Wolf

Reputation: 6316

Cast a Typescript class to a string?

I have a Typescript interface that I need to convert to a string to send to an API endpoint.

This is the object (as printed from the console using console.log()

{name: "John", avatarId: 1, forwardRelationship: "WIFE", reverseRelationship: "HUSBAND"}

I initially tried JSON.stringify() to turn it into a string that the API would be happy with which outputs the following:

{"name":"John","avatarId":1,"forwardRelationship":"WIFE","reverseRelationship":"HUSBAND"}

The API needs just the one string though so:

"{name:John,avatarId:1,forwardRelationship:WIFE,reverseRelationship:HUSBAND}"

Is there a function I do this with shorthand? Or do Need to build the string up manually using each property?

Upvotes: 1

Views: 64

Answers (1)

Tobias Miosczka
Tobias Miosczka

Reputation: 213

I would recommend you to change the backend to accept valid JSON. If you really need to use this format you could use the following method:

   const text: string = "\"" + JSON.stringify(yourObject).replace(/"/g,"") + "\"";

Upvotes: 2

Related Questions