Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON in QML [duplicate]

The relevant Qt doc should be this. But it makes no mention of QML. Yet on many places on the net I find usage of functions like JSON.parse in QML JS. Is there such a function and how do I use it?

I'd just ask for a link to documentation but that's considered off-topic here.

like image 291
Stefan Monov Avatar asked Jan 27 '17 18:01

Stefan Monov


1 Answers

Parsing JSON in QML is no different than parsing JSON in Javascript, because QML provides an environment based on ECMAScript (link) with some modifications especially for QML.

So you can use the in-built JSON.parse() function. The following example is possible in QML:

import QtQuick 2.7
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Component.onCompleted: {
        var JsonString = '{"a":"A whatever, run","b":"B fore something happens"}';
        var JsonObject= JSON.parse(JsonString);

        //retrieve values from JSON again
        var aString = JsonObject.a;
        var bString = JsonObject.b;

        console.log(aString);
        console.log(bString);
    }
}

And this is the reason why the Qt docs don't state anything about this particular function:

The standard ECMAScript built-ins are not explicitly documented in the QML documentation. For more information on their use, please refer to the ECMA-262 5th edition standard or one of the many online JavaScript reference and tutorial sites, such as the W3Schools JavaScript Reference (JavaScript Objects Reference section)

Source

like image 173
DuKes0mE Avatar answered Nov 13 '22 11:11

DuKes0mE