0

I am developing an Angular 4 application which speaks to a REST API by getting and sending JSON requests.

When I am preparing JSON requests for posting I am doing a lot of manual work to build the JSON..

I AM SURE THERE MUST BE A BETTER WAY THAN THE BELOW using a library or typescript trick.. But haven't been able to find one and am looking for recommendations.

const addressJson = ' { \n ' + this.jsonFormatField('Address', serviceAddress.address) + ',' +
            this.jsonFormatField('Address2', serviceAddress.address2) + '\n,' +
            this.jsonFormatField('City', address3) + '\n,' +

2 Answers 2

4

Have you tried JSON.stringify? It accepts a regular JavaScript object as input and produces a string containing the associated JSON for it.

Sign up to request clarification or add additional context in comments.

2 Comments

I guess my problem is in my app I have a JSON object X with slightly different properties to the JSON object Y the API I am posting to needs... I guess I could create an object in the structure of Y then fill in the properties from X which would be a bit cleaner?
You should definitely do that. Usually for the request and response data to an API you need a dto, which are lightweight objects tailored to the API in question. The types used by the application don't have to map to this exactly, and in fact, they might add a lot of baggage from the various frameworks you use. So it's a good idea to have some sort of explicit translation between types used in the client application, and types understood by the API. When it comes to adding and removing fields this pays off.
1

Angular will serialise an object to JSON for you:

const address = {
    Address: serviceAddress.address,
    Address2: serviceAddress.address2,
    City: address3
};

http
  .post('/your/rest/endpoint', address)
  // subscribe() is still necessary when using post().
  .subscribe(...);

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.