I need to access to a Json string inside my qml code, now if the field is known is is easy.
Given {"c1":320, "c2":256, "c3":128}
I can
function getC1(jsonstr)
{
const obj = JSON.parse(jsonstr);
return obj.c1;
}
But what if I don't know in advance which field to access and have it in a variable.
like obj["c1"] or obj[variable] syntaxes are not working. Is there a way?
I disagree with your assertion that those other methods you tried don't work. Here is what I did:
property string json: '{"c1":320, "c2":256, "c3":128}'
function getC1(jsonstr)
{
const obj = JSON.parse(jsonstr);
const key = "c1";
console.log(obj.c1);
console.log(obj["c1"]);
console.log(obj[key]);
}
Component.onCompleted:
{
getC1(json);
}
And here is the output:
qml: 320
qml: 320
qml: 320
So all 3 methods produce the desired output.