1

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?

2
  • 4
    Your API requires invalid JSON as input? I would heartily suggest you make it accept valid JSON instead. Commented Jul 30, 2020 at 13:24
  • I completely agree with @VLAZ here. If you really need to send your data like this, you will have to build up the string manually, there is no shorthand for that. Commented Jul 30, 2020 at 13:36

1 Answer 1

2

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,"") + "\"";
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.