在 QML 中解析 JSON
相关的Qt doc应该是this.但它没有提到 QML.然而,在网上的许多地方,我发现在 QML JS 中使用了像 JSON.parse
这样的函数.有没有这样的功能,如何使用?
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.
推荐答案
在 QML 中解析 JSON 与解析 Javascript 中的 JSON,因为 QML 提供了一个基于 ECMAScript 的环境 (link) 进行了一些修改,特别是针对 QML.
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.
所以你可以使用内置的 JSON.parse()
函数.在 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);
}
}
这就是 Qt 文档没有说明这个特定功能的原因:
And this is the reason why the Qt docs don't state anything about this particular function:
标准的 ECMAScript 内置插件没有明确记录在 QML 文档中.有关其使用的更多信息,请参阅 ECMA-262 第 5 版标准或众多在线 JavaScript 参考和教程网站之一,例如 W3Schools JavaScript 参考(JavaScript 对象参考部分)
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)
来源
相关文章