[SalesForce] Parsing JSON string value returned from APEX in LWC

I am receiving JOSN string in the following format

{"data":{"meta":{"resultCode":null,"message":null},"data":[{"code":"$RFG","Token":288}]}}

I am trying to fetch value of code and Token from the JSON string and I want to use it in LWC html. I tried in may ways but I am not able to fetch the value as expected. Somewhere I am missing some part. Please let me know where I am going wrong.

import { LightningElement, api, wire, track } from 'lwc';
import getToken from '@salesforce/apex/ProcessToken.getToken';
export default class tokenProcess extends LightningElement {
    @track ww;
    @api recordId;
    @wire (getToken, {Id : '$recordId'})
    entitlement(tokenDetails, error){
     if(tokenDetails)
     {
      
        this.ww = tokenDetails.data;
        console.log('DDDDD@@@@@@@'+ this.ww);
       this.ww.data.forEach(meta => {
        console.log(meta.code, meta.Token);
    });
    
  } 
     else if(error)
     {
        
    }
}
}

In Console:

DDDDD@@@@@@@ : {"meta":{"resultCode":null,"message":null},"data":[{"code":"$RFG","Token":288}]}

After this I am not able to fetch it.

Best Answer

first, it would be important to know what type your getToken method is returning from apex. (String, Map<String,Object>, List, etc, etc...)

this will allow you to understand what the client receives, and how to handle the response.

based on the above, you might, or might not need to parse the string in order to convert it to an object. if you are expecting multiple code/token objects in your data array and need to fetch them all separately, you can do it in a forEach loop as you seem to be already doing, if you are only expecting 1, then, instead you could use a Array.prototype.find() to get the objects and assign to variables accordingly.

Related Topic