JSONListModel

From Qt Wiki
Revision as of 14:32, 23 February 2015 by Maintenance script (talk | contribs)
Jump to navigation Jump to search

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:

<br />{ &quot;store&amp;quot;: {<br /> &quot;book&amp;quot;: [<br /> { &quot;category&amp;quot;: &quot;reference&amp;quot;,<br /> &quot;author&amp;quot;: &quot;Nigel Rees&amp;quot;,<br /> &quot;title&amp;quot;: &quot;Sayings of the Century&amp;quot;,<br /> &quot;price&amp;quot;: 8.95<br /> },<br /> { &quot;category&amp;quot;: &quot;fiction&amp;quot;,<br /> &quot;author&amp;quot;: &quot;Evelyn Waugh&amp;quot;,<br /> &quot;title&amp;quot;: &quot;Sword of Honour&amp;quot;,<br /> &quot;price&amp;quot;: 12.99<br /> },<br /> { &quot;category&amp;quot;: &quot;fiction&amp;quot;,<br /> &quot;author&amp;quot;: &quot;Herman Melville&amp;quot;,<br /> &quot;title&amp;quot;: &quot;Moby Dick&amp;quot;,<br /> &quot;isbn&amp;quot;: &quot;0-553-21311-3&amp;quot;,<br /> &quot;price&amp;quot;: 8.99<br /> },<br /> { &quot;category&amp;quot;: &quot;fiction&amp;quot;,<br /> &quot;author&amp;quot;: &quot;J. R. R. Tolkien&amp;quot;,<br /> &quot;title&amp;quot;: &quot;The Lord of the Rings&amp;quot;,<br /> &quot;isbn&amp;quot;: &quot;0-395-19395-8&amp;quot;,<br /> &quot;price&amp;quot;: 22.99<br /> }<br /> ],<br /> &quot;bicycle&amp;quot;: {<br /> &quot;color&amp;quot;: &quot;red&amp;quot;,<br /> &quot;price&amp;quot;: 19.95<br /> }<br /> }<br />}<br />

We can write:

<br /> JSONListModel {<br /> id: jsonModel1<br /> source: &quot;jsonData.txt&amp;quot;<br /> // All books in the store object<br /> query: &quot;$.store.book[*]&quot;<br /> }

JSONListModel {<br /> id: jsonModel2<br /> source: &quot;jsonData.txt&amp;quot;<br /> // Books less than $10<br /> query: &quot;$..book[?(

.price&lt;10)]"
} JSONListModel {
id: jsonModel3
json: '[ {"label&quot;: "Answer&quot;, "value&quot;: "42&quot;}, {"label&quot;: "Pastis&quot;, "value&quot;: "51&quot;}, {"label&quot;: "Alsace&quot;, "value&quot;: "67&quot;}, {"label&quot;: "Alsace&quot;, "value&quot;: "68&quot;} ]'
// Labels starting with 'A'
query: "$[?(

.label.charAt(0)==='A')]&quot;<br /> }<br />

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 />