How to use JavaScript to parse JSON in QML applications

Source: Internet
Author: User
Tags i18n

Many qml should need access to Web services. We can use JavaScript to parse out the JSON data we need and show them. In today's example, we will show how to implement it?


We can create a basic "QML app with simple UI (qmlproject)" and name Our app "Baidutranslator". The APIs we will use are:


Http://openapi.baidu.com/public/2.0/bmt/translate?client_id=2hG67S2yRm5chkr62j2IEmYL&from=auto&to=auto &q=%e4%bd%a0%e5%a5%bd

The results shown are:

{"from": "zh", "to": "en", "trans_result": [{"src": "\u4f60\u597d", "DST": "Hello"}]}

We can use this API interface to get Chinese or English translation, even we can get a complete sentence in Chinese or English. The result returned by the above interface is in JSON format.

To be able to parse the JSON format we got, we created a "jsonparser.js" file:


var URL = "Http://openapi.baidu.com/public/2.0/bmt/translate?client_id=2hG67S2yRm5chkr62j2IEmYL&from=auto    &to=auto&q= "; function startparse (keyword, callback) {var doc = new XMLHttpRequest (); Doc.onreadystatechange = function () {if (doc.readystate = = xmlhttprequest.headers_received) {} else if (do C.readystate = = = Xmlhttprequest.done) {if (doc.status! =) {Console.log ("!!!            Network connection failed! ")}                else {Console.log ("got some results!"); if (Doc.responsetext = = null) {} else {console.log ("Result:", DOC.RESPO                    Nsetext) var json = Json.parse (' + doc.responsetext+ ');                    json["status"] = "OK";                Callback.update (JSON);    }}}} doc.open ("GET", URL + keyword); Doc.send ();}


We send requests through "startparse" and parse the results we get with json.parse (). We return to our QML design through "callback.update".


The design of "main.qml" is as follows:


Import QtQuick 2.0import ubuntu.components 1.1import "Jsonparser.js" as api/*!  \brief MainView with a Label and Button Elements.*/mainview {id:root//ObjectName for functional testing purposes (AUTOPILOT-QT5) ObjectName: "MainView"//note!    ApplicationName needs to match the "name" field of the click Manifest ApplicationName: "Baidutranslator.liu-xiao-guo" /* The enables the application to change orientation when the device is rotated.    The default is False.    *///automaticorientation:true//Removes the old toolbar and enables new features of the new header. Usedeprecatedtoolbar:false width:units.gu (height:units.gu) function Update (JSON) {Console.log ("        JSON: "+ json.stringify (JSON));        Mymodel.clear (); if (json.trans_result!== undefined && json.trans_result.length!== undefined) {for (var idx = 0; i DX < json.trans_result.length; idx++) {if (Json.trans_result[idx].dst) {console.log (' meaning: ' + json.trans_result[idx].dst);                Mymodel.append ({"meaning": json.trans_result[idx].DST});        }}}} else {mymodel.clear (); }} page {title:i18n.tr ("Baidu translator") Listmodel {Id:mymodel} colum            n {spacing:units.gu (1) Anchors {margins:units.gu (2) fill:parent                } TextField {id:input placeholdertext: "Please input a word"                    Width:parent.width text: "Hello" ontextchanged: {mymodel.clear ();                var json = Api.startparse (input.text, Root); }} Button {Id:doit width:parent.width text:i18n.tr         ("Translate") onclicked: {           var json = Api.startparse (input.text, Root);  }} ListView {Id:listview width:parent.width height:                    Parent.height-input.height-doit.height Model:mymodel Delegate:text { Text:modeldata}}}}

Here we pass the " Update"To update our ListView.




The source code for all projects is: Git clone https://gitcafe.com/ubuntu/baidutranslator.git


How to use JavaScript to parse JSON in QML applications

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.