Forums

OverviewFelgo 2 Support (Qt 5) › Help needed for simple JSON.parse?

Viewing 13 posts - 1 through 13 (of 13 total)
  • Author
    Posts
  • #18091

    Niyazi

    Hi,

    I am testing Felgo qml json. I set small example but I cannot get the value to show in List View. I need help?

     

    import Felgo 3.0
    import QtQuick 2.0
    import QtQuick.Controls 1.2
    
    App {
        id: appRoot
    
        Page {
            id: myPage
            anchors.fill: parent
            Item {
                id: myJson
                x: 0
                y: 150
                width: 300
                height: 400
    
                ListModel {
                    id: model
                }
    
                ListView {
                    id: listview
                    anchors.fill: parent
                    model: model
                    delegate: Text {
                        color: "red"
                        text: listdata
                    }
                }
    
                Button {
                    anchors.bottom: parent.bottom
                    width: parent.width
                    text: "Get Data"
                    onClicked: myPage.getData
                }
    
    
                function getData() {
                    var xmlhttp = new XMLHttpRequest();
                    var url = "https://api.ipify.org?format=json"
    
                    xmlhttp.onreadystatechange=function() {
                        if (xmlhttp.readyState === XMLHttpRequest.DONE && xmlhttp.status === 200) {
                            myPage.myFunction(xmlhttp.responseText);
                        }
                    }
                    xmlhttp.open("GET", url, true);
                    xmlhttp.send();
                }
    
                function myFunction(response) {
                    var arr = JSON.parse(response);
                    for(var i = 0; i < arr.length; i++) {
                        listview.model.append( {listdata: arr[i].ip  })
                    }
                }
    
            }
        }
    }
    
    
    
    
    

     

    #18098

    Günther
    Felgo Team

    Hi,

    there are several mistakes in your code, please have a look:

    import Felgo 3.0
    import QtQuick 2.0
    import QtQuick.Controls 1.2
    
    App {
        id: appRoot
    
        Page {
            id: myPage
            anchors.fill: parent
            Item {
                id: myJson
                x: 0
                y: 150
                width: 300
                height: 400
    
                ListModel {
                    id: model
                }
    
                ListView {
                    id: listview
                    anchors.fill: parent
                    model: model
                    delegate: Text {
                        color: "red"
                        text: listdata
                    }
                }
    
                Button {
                    anchors.bottom: parent.bottom
                    width: parent.width
                    text: "Get Data"
                    onClicked: myPage.getData() // WRONG: myPage.getData
                }
            }
    
            // moved these functions from within Item { } to Page { }, as we trigger them with e.g. myPage.getData()
            function getData() {
                var xmlhttp = new XMLHttpRequest();
                var url = "https://api.ipify.org?format=json"
                xmlhttp.onreadystatechange=function() {
                    if (xmlhttp.readyState === XMLHttpRequest.DONE && xmlhttp.status === 200) {
                        myPage.myFunction(xmlhttp.responseText);
                    }
                }
                xmlhttp.open("GET", url, true);
                xmlhttp.send();
            }
    
            function myFunction(response) {
              var arr = JSON.parse(response);
    
              // the json response is not an array, but a single JSON object, so this does not work:
              //  for(var i = 0; i < arr.length; i++) {
              //    listview.model.append({listdata: arr[i].ip })
              //  }
              listview.model.append({ listdata: arr.ip } )
            }
        }
    }
    

    Best,
    Günther

    #18106

    Niyazi

    Thanks Günther,

    Is working now. And I realize my mistakes. 🙂

    #18107

    Niyazi

    This is whole working code (Just changed the API):

    import Felgo 3.0
    import QtQuick 2.0
    import QtQuick.Controls 1.2
    
    App {
        id: appRoot
    
        Page {
            id: myPage
            anchors.fill: parent
    
            Item {
                id: myItem
                y: 150
                width: parent.width
                height: parent.height - y
    
                ListModel {
                    id: model
                }// ListModel
    
                ListView {
                    id: listView
                    model: model
                    delegate: Text {
    
                        color: "red"
                        text: listdata
                    }
                } // ListView
    
                Button{
                    id: requestJsonBtn
                    anchors.bottom: parent.bottom
                    width: parent.width
                    text: "Get Json Data"
                    onClicked: {
                        myPage.getJsonData()
                    }
                }// Button
            } // Item
    
            function getJsonData() {
                var myHttpRequest = new XMLHttpRequest;
                console.debug("new XMLHttpRequest")
                var url = "https://jsonplaceholder.typicode.com/posts/1"
                myHttpRequest.onreadystatechange = function() {
                    console.debug("onreadystatechange")
                    if (myHttpRequest.readyState === XMLHttpRequest.DONE && myHttpRequest.status === 200) {
                        var arr = JSON.parse(myHttpRequest.responseText)
                        console.debug("myHttpRequest.responseText")
                        //listView.model.append( {listdata: arr.ip  })
                        listView.model.append( {listdata: arr.userId +" "+ arr.id +" "+ arr.title +" "+ arr.body  })
                    } else
                    {
                        console.debug("Error")
                    }
                }
                myHttpRequest.open("GET", url, true)
                myHttpRequest.send();
            } // getJsonData
    
    
        } // Page
    } // App
    

     

    #18804

    Adelar

    Hi guys,

     

    Sorry, but I’m testing this code, and all I get is this error:

     

    ReferenceError: listdata is not defined

     

    Can somebody point me to the right path ?

     

    Thanks in advance

     

     

    #18814

    Günther
    Felgo Team
    #18815

    Niyazi
    #18823

    Adelar

    Hello,
    Thanks for the reply … But I’ve read, followed and tested the mentioned example (Rest Services Qt V-play weather …) and when trying to modify to bring data to a list, I could not make it work at all.
    In the above responses, it is mentioned that return is an object, not an array:
    // the json response is not an array, but a single JSON object, so this does not work:

    But strangely, when I came to iterate as an array, and did not try to assign as an object directly, the code worked. And actually, I get a json object as a return. So I was a little lost, not knowing the correct procedure to adopt.

    I think it would be interesting to include more examples dealing with json returns for lists, in a simple way. So,  we could learn more clearly and simply.

    Thank you.

    #18825

    Adelar

    Continuing…

    This code work’s fine… And I not assign a json object, but iterate through an array…

    import QtQuick 2.0
    import QtQuick.Controls 1.2
    
    App {
        id: window
        visible: true
        width: 640
        height: 480
        //title: qsTr("Rest Test")
    
        Item {
            width: 400
            height: 350
            clip: true
            anchors.centerIn: parent
            id: lista
    
            ListModel {
                id: model
            }
    
            ListView {
                id: listview
                anchors.fill: parent
                model: model
                delegate: Text {
                    //color: "red"
                    text: jsondata
                }
            }
        }
    
        Button {
            anchors.top: lista.bottom
            anchors.left: lista.left
            width: lista.width
            text: "GET Data"
            onClicked: {
                var xmlhttp = new XMLHttpRequest();
                var url = "http://ec2-18-231-19-180.sa-east-1.compute.amazonaws.com/ords/infformo/v1/estados/";
    
                xmlhttp.onreadystatechange=function() {
                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                        myFunction(xmlhttp.responseText);
                    }
                }
                xmlhttp.open("GET", url, true);
                //xmlhttp.setRequestHeader('Authorization', 'Basic Q1hLRURwNXA2cW1NUk1nVU9HZHgyUHdIYVlyRTIwa3Y6');
                xmlhttp.send();
    
                function myFunction(json) {
                    var obj = JSON.parse(json);
                    //console.log(xmlhttp.responseText);
                    for (var i = 0; i < obj.items.length; i++){
                        listview.model.append({jsondata: obj.items[i].nome })
    
                    }
    
                }
    
            }
        }
    } // App
    

     

    #18891

    Niyazi

    So whats the problem. This is a “var obj = JSON.parse(json);” son object. Object can be anything. It could be a string, real, or an array. So Gunther said:

    (// the json response is not an array, but a single JSON object, so this does not work: ). meaning is in my example json can return only single item as object. and is not return an array. In your code however the json response returns an object array.

    Look at here: https://www.copterlabs.com/json-what-it-is-how-it-works-how-to-use-it/

     

    So in your above example “And I not assign a json object, but iterate through an array…” you assign a json object in here:

    var obj = JSON.parse(json);

     

    Then you iterate through an object array.

    for (var i = 0; i < obj.items.length; i++){

     

    Your return is not a single object like in my example which Gunter stated in his post. Your json cannot return single object.

    All depends on the what is the json data. If you know the json data so you can use as you wish. Such as as single object or and object array.

     

     

    v

     

    #18921

    Adelar

    thank you so much. Now, I understood clearly.

     

    Regards

     

     

    #18922

    Niyazi

    Your welcome.

    #18934

    Yusuf Umut Piynar
Viewing 13 posts - 1 through 13 (of 13 total)

RSS feed for this thread

You must be logged in to reply to this topic.

Voted #1 for:

  • Easiest to learn
  • Most time saving
  • Best support

Develop Cross-Platform Apps and Games 50% Faster!

  • Voted the best supported, most time-saving and easiest to learn cross-platform development tool
  • Based on the Qt framework, with native performance and appearance on all platforms including iOS and Android
  • Offers a variety of plugins to monetize, analyze and engage users
FREE!
create apps
create games
cross platform
native performance
3rd party services
game network
multiplayer
level editor
easiest to learn
biggest time saving
best support