Home > Software design >  JSON string won't print to console
JSON string won't print to console

Time:05-24

I have this service:

getCert(p: string): Promise<string> {
  return ApiService.getData(this.apiUrl   p   this.certEndpoint).then(
    (response) => response.data
  );
}

This is an example of data:

{
    "state": "success",
    "message": "Message received."
}

If I return response.data.state or response.data.message I get the relevant value.

If I call it with this:

async componentDidMount() {
    const queryString = require('query-string');
    const parsed = queryString.parse(location.search);
    return this.docListingService.getPks(parsed.policy).then(async pks => {
        this.setState({ isLoading: false, packs });
        this.certService.getCert(parsed.policy).then( response => {
            console.log('RESPONSE: '   response);
        });
        return pks;
    }).catch((error) => {
        this.loggingService.logError('Error returning Docs '   error);
        this.setState({ errorOccured: true});
    });
}

response is a string but my consle.log prints RESPONSE [object Object]. I tried console.log('RESPONSE: ' response.state); and console.log('RESPONSE: ' response.message); but they error. As does:

console.log('RESPONSE: '   JSON.parse(response));

How do I resolve this?

CodePudding user response:

console.log() accepts as many arguments as you like. So you can just use it like this:

console.log('response ', response)

If you want to log multiple variables, you can do it like this:

console.log(variable1, variable2, variable3, 'some string', variable4);

CodePudding user response:

you have a bug in console.log of your code, you are trying to concat a string and json object. you can try this code

console.log('response ', JSON.parse(response));

//or

console.log('response ', JSON.parse(response).data.message);

//or

console.log('response '   JSON.parse(response).data.message);

CodePudding user response:

Just use:

JSON.stringify(response)

This will show the Object structure as string value.

  • Related