JSON dot notation in LWC/Javascript

apexjavascriptjsonlightning-web-components

I've tried searching for a solution, and I think my syntax is correct here, but I can't achieve the desired result.

I'm querying an API and getting a returned JSON that looks like this:

{
  "StudyFieldsResponse":{
    "APIVrs":"1.01.05",
    "DataVrs":"2022:03:13 23:05:33.643",
    "Expression":"Lyell Immunopharma",
    "NStudiesAvail":407561,
    "NStudiesFound":1,
    "MinRank":1,
    "MaxRank":20,
    "NStudiesReturned":1,
    "FieldList":[
      "LastUpdatePostDate",
      "EnrollmentCount",
      "NCTId",
      "OrgFullName",
      "BriefTitle",
      "OfficialTitle",
      "Phase"
    ],

I'd like to get the NStudiesReturned. The data is being passed from Apex to the LWC, but I cannot seem to access it via dot notation. Am I doing something wrong here? Here's what I've tried:

Serializing the Apex before returning the string and
2x Parsing

 @track trials;
 @track error;
clinicalTrialsFieldQuery()
            .then(result => {
                this.trials = result;
                this.test = this.trials.StudyFieldsResponse.NStudiesAvail;
                // this.test = this.trials.StudyFieldsResponse.NStudiesAvail;
                console.log(this.trials);
                console.log(this.test);
              
            })
            .catch(error => {
                this.error = error;
            });

Best Answer

maybe the LWC see it as a string, try deserializing the JSON from the Apex and sending the result to it, it should work.

Add these sub classes in your apex controller

public with sharing class StudyFieldsResponse {
@auraEnabled public StudyFields StudyFieldsResponse {get;set;} }

public with sharing class StudyFields {
@auraEnabled public string aPIVrs {get;set;}
@auraEnabled public String dataVrs {get;set;}
@auraEnabled public string expression {get;set;}
@auraEnabled public Integer nStudiesAvail {get;set;}
@auraEnabled public Integer nStudiesFound {get;set;}
@auraEnabled public Integer minRank {get;set;}
@auraEnabled public Integer maxRank {get;set;}
@auraEnabled public Integer nStudiesReturned {get;set;}
@auraEnabled public List<String> FieldList {get;set;}}

and in your apex method use this to deserialize the JSON:

StudyFieldsResponse resp = (StudyFieldsResponse) JSON.deserializeStrict(yourJsonStringHere, StudyFieldsResponse.class);

then return resp to lwc and use the dot notation to acess your value

Related Topic