arraysjsonqml

How to access the element of a JSON array by index


In a QML project, I need to read and access the elements of an array of objects from this JSON file:

{
  "params": [
    {
      "id": "1",
      "tag": "aaa",
      "name": "aaaaaa",
      "value": "1.23"
    },
    {
      "id": "2",
      "tag": "bbb",
      "name": "bbbbbb",
      "value": "4.56"
    }
  ]
}

I can do it if I have a single object, but I cannot make it work with an array.

This is what I am doing:

var jsonObj = JSON.parse(dataFile);
var i = 0;   // array index
var elem = jsonObj.valueOf("params")[i]
console.log("params[" + i + "]: " + elem)  //  TypeError: Cannot read property 'name' of undefined
console.log("params[" + i + "].id: " + elem.id)  // TypeError: Cannot read property 'id' of undefined

Note that I am not trying to access the 'name' field.

How can I access the object fields?

Note: My question includes the valueOf function, which is not mentioned here.


Solution

  • var jsonObj = JSON.parse(dataFile); 
    var i = 0; 
    
    var elem = jsonObj.params[i];
    
    if (elem) { 
        console.log(i + ".id: " + elem.id); 
    } else {
        console.log("No element at " + i);
    }
    

    You can use jsonObj.params[i] instead of use valueOf method. Accessing directly elem.id can caused TypeError if elem is undefined value.