LWC – Fixing Undefined JSON Parse Responses in Apex

javascriptlightning-web-components

I am writing a pretty simple lwc component that should display JSON data. The apex method makes an http call and gets a response. using the response.getBody method, this returns a string. My apex method declares a string, and the response body is assigned to that string. The lwc component calls that method imperatively and I assign that return to a let variable. When I parse it, to presumably change the string to json, I get object object. I have tried many iterations of this (which I will not post) such as stringify and then parsing, but it ends up with double json parsing. Here's my issue, when I try to iterate through that returned string (json) it is reading it like a string array, meaning , { data : [ id:001] } but returns … => console.log(array[0]) => '}' . I need to be able to return the appropriate key/value pairs.

JSON

{
  "data" : [
    {
      "test1" : "079",
      "test2" : "00100",
      "test3" : "4352",
      "test4" : "543",
      "test5" : "234642",
      "test6" : 2719,
      "test7" : "hello",
      "test8" : "0444542",
      "test9" : "test hi one"
    },
    {
      "test1" : "24566134",
      "test2" : "0102",
      "test3" : "66543",
      "test4" : "244549",
      "test5" : "2666549",
      "test6" : 24525,
      "test7" : "once",
      "test8" : "595552",
      "test9" : "test hi two"
    }

  ]

}

Apex

        String jsonString;
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://fake.com');
        req.setMethod('GET');
        Http http = new Http();
        HTTPResponse res = http.send(req);
        jsonString = res.getBody();
        return jsonString

JS

handleClick(){
returnVal({})
  .then(result => {
    let valJson = JSON.parse(JSON.stringify(result);
    }
    // JSON.parse alone returns [object object]. if I try to do valJson[0]. returns undefined
    // the current iteration valJson[0] literally returns '{'

}

Best Answer

You need to fetch the values like this:-

handleClick(){
  returnVal({})
    .then(result => {
      let valJson = JSON.parse(JSON.stringify(result));
      valJson.data.forEach(element => {
        console.log(element.test1);
      });
  }
}

because valJson is having an attribute called data which is of array type. So you need to itearte on it find the values.

You were trying to do valJson[0] which is not valid.

UPDATE

As per comment, method is returning stringified value, so slight change in above code. changed let valJson = JSON.parse(JSON.stringify(result); to let valJson = JSON.parse(result);

handleClick(){
      returnVal({})
        .then(result => {
          let valJson = JSON.parse(result);
          valJson.data.forEach(element => {
            console.log(element.test1);
          });
      }
    }

Another Update

I have tried replicating your problem in my org. I created a method as below:-

@AuraEnabled
    public static string jsonReturn(){
        string value = '{"data":[{"test1":"079","test2":"00100","test3":"4352","test4":"543","test5":"234642","test6":2719,"test7":"hello","test8":"0444542","test9":"test hi one"},{"test1":"24566134","test2":"0102","test3":"66543","test4":"244549","test5":"2666549","test6":24525,"test7":"once","test8":"595552","test9":"test hi two"}]}';
        return value;
    }

then in my lwc js file

handleJSON() {

        jsonReturn().then(res => {
            console.log(res);
            console.log(JSON.parse(res));
            console.log(JSON.parse(res).data);
            JSON.parse(res).data.forEach(element => {
                console.log(element);
            });
        }).catch(error => {
            console.log(error);
        })

    }

and got this in log:- enter image description here