JSONListModel
JSONListModel is a pure-QML component that allows using JSON data as datasource for a QML ListView.
Code
The JSONListModel code is Open Source and available under the MIT license at:
"github.com/kromain/qml-utils":https://github.com/kromain/qml-utils
Features
- mimics the XMLListModel component by providing similar API and properties
- supports both source-based and string-based JSON data
- support complex JSON documents and queries via JSONPath (XPath for JSON)
Example
With a file jsonData.txt containing:
{ "store": {
"book": [
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{ "category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{ "category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}
We can write:
<br /> JSONListModel {<br /> id: jsonModel1<br /> source: "jsonData.txt&quot;<br /> // All books in the store object<br /> query: "$.store.book[*]"<br /> }
JSONListModel {<br /> id: jsonModel2<br /> source: "jsonData.txt&quot;<br /> // Books less than $10<br /> query: "$..book[?(
.price<10)]"
}
JSONListModel {
id: jsonModel3
json: '[ {"label": "Answer", "value": "42"}, {"label": "Pastis", "value": "51"}, {"label": "Alsace", "value": "67"}, {"label": "Alsace", "value": "68"} ]'
// Labels starting with 'A'
query: "$[?(.label.charAt(0)==='A')]"
}
And use it in views and delegates like this:
<br /> ListView {<br /> model: jsonModel1.model
delegate: Component {<br /> Text {<br /> // Can be any of the JSON properties: model.author, model.price, etc.<br /> text: model.title<br /> }<br /> }<br />