0

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 '{'

}

1
  • Can you show the exact format of data which was returned from the backend to JS? Because the array was not returned from the backend so you can not iterate on it directly.
    – Gopal
    Jan 11, 2023 at 7:43

2 Answers 2

2

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

7
  • this does not work. if i do console.log(result + valJson). it will show the full json data. if i do a console.log(valJson.data) it shows undefined. when i declare that foreach if wont even run a console.log('foo) inside of it, because there is no elements for valJson.data.
    – sesanc
    Jan 11, 2023 at 6:57
  • ps: the above will only work and return [object object] for valJson if I remove the JSON.stringify and only leave the JSON.parse. with the stringify, it fails outright.
    – sesanc
    Jan 11, 2023 at 7:00
  • @sesanc, I corrected my answer. Jan 11, 2023 at 7:04
  • as I tried to point out in my 'ps; this wont work. if i do a console.log(valJson.data) returns undefined. if i write the foreach and do a console.log('foo') inside, it wont print because there is no 'element' for valJson.data. **this is after removing the JSON.stringify
    – sesanc
    Jan 11, 2023 at 7:15
  • I've tried doing Object.entries(valJson).forEach(element) and it seems to be printing out a character array this way. my output is literally " console test object entries0,{ console test object entries1," console test object entries2,i "
    – sesanc
    Jan 11, 2023 at 7:19
0

You can try this

Explination: First we will parse the backend result then we will itreate on valJson.data

handleClick(){
  returnVal()
  .then(result => {
      let valJson = JSON.parse(result);
      valJson.data.forEach((d)=>{
         console.log('Record:',d);
      })
    }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .