Skip to main content

json_glib/auto/
path.rs

1// This file was generated by gir (https://github.com/gtk-rs/gir)
2// from gir
3// from gtk-girs (https://github.com/gtk-rs/gir-files)
4// DO NOT EDIT
5
6use crate::{Node, ffi};
7use glib::translate::*;
8
9glib::wrapper! {
10    /// `JsonPath` is a simple class implementing the JSONPath syntax for extracting
11    /// data out of a JSON tree.
12    ///
13    /// While the semantics of the JSONPath expressions are heavily borrowed by the
14    /// XPath specification for XML, the syntax follows the ECMAScript origins of
15    /// JSON.
16    ///
17    /// Once a `JsonPath` instance has been created, it has to compile a JSONPath
18    /// expression using [`compile()`][Self::compile()] before being able to match it to
19    /// a JSON tree; the same `JsonPath` instance can be used to match multiple JSON
20    /// trees. It it also possible to compile a new JSONPath expression using the
21    /// same `JsonPath` instance; the previous expression will be discarded only if
22    /// the compilation of the new expression is successful.
23    ///
24    /// The simple convenience function [`query()`][Self::query()] can be used for
25    /// one-off matching.
26    ///
27    /// ## Syntax of the JSONPath expressions
28    ///
29    /// A JSONPath expression is composed by path indices and operators.
30    /// Each path index can either be a member name or an element index inside
31    /// a JSON tree. A JSONPath expression must start with the `$` operator; each
32    /// path index is separated using either the dot notation or the bracket
33    /// notation, e.g.:
34    ///
35    /// ```text
36    /// // dot notation
37    /// $.store.book[0].title
38    ///
39    /// // bracket notation
40    /// $['store']['book'][0]['title']
41    /// ```
42    ///
43    /// The available operators are:
44    ///
45    /// * The `$` character represents the root node of the JSON tree, and
46    ///   matches the entire document.
47    ///
48    /// * Child nodes can either be matched using `.` or `[]`. For instance,
49    ///   both `$.store.book` and `$['store']['book']` match the contents of
50    ///   the book member of the store object.
51    ///
52    /// * Child nodes can be reached without specifying the whole tree structure
53    ///   through the recursive descent operator, or `..`. For instance,
54    ///   `$..author` matches all author member in every object.
55    ///
56    /// * Child nodes can grouped through the wildcard operator, or `*`. For
57    ///   instance, `$.store.book[*].author` matches all author members of any
58    ///   object element contained in the book array of the store object.
59    ///
60    /// * Element nodes can be accessed using their index (starting from zero)
61    ///   in the subscript operator `[]`. For instance, `$.store.book[0]` matches
62    ///   the first element of the book array of the store object.
63    ///
64    /// * Subsets of element nodes can be accessed using the set notation
65    ///   operator `[i,j,...]`. For instance, `$.store.book[0,2]` matches the
66    ///   elements 0 and 2 (the first and third) of the book array of the store
67    ///   object.
68    ///
69    /// * Slices of element nodes can be accessed using the slice notation
70    ///   operation `[start:end:step]`. If start is omitted, the starting index
71    ///   of the slice is implied to be zero; if end is omitted, the ending index
72    ///   of the slice is implied to be the length of the array; if step is
73    ///   omitted, the step of the slice is implied to be 1. For instance,
74    ///   `$.store.book[:2]` matches the first two elements of the book array
75    ///   of the store object.
76    ///
77    /// More information about JSONPath is available on Stefan Gössner's
78    /// [JSONPath website](http://goessner.net/articles/JsonPath/).
79    ///
80    /// ## Example of JSONPath matches
81    ///
82    /// The following example shows some of the results of using `JsonPath`
83    /// on a JSON tree. We use the following JSON description of a bookstore:
84    ///
85    /// ```json
86    /// { "store": {
87    ///     "book": [
88    ///       { "category": "reference", "author": "Nigel Rees",
89    ///         "title": "Sayings of the Century", "price": "8.95"  },
90    ///       { "category": "fiction", "author": "Evelyn Waugh",
91    ///         "title": "Sword of Honour", "price": "12.99" },
92    ///       { "category": "fiction", "author": "Herman Melville",
93    ///         "title": "Moby Dick", "isbn": "0-553-21311-3",
94    ///         "price": "8.99" },
95    ///       { "category": "fiction", "author": "J. R. R. Tolkien",
96    ///         "title": "The Lord of the Rings", "isbn": "0-395-19395-8",
97    ///         "price": "22.99" }
98    ///     ],
99    ///     "bicycle": { "color": "red", "price": "19.95" }
100    ///   }
101    /// }
102    /// ```
103    ///
104    /// We can parse the JSON using [`Parser`][crate::Parser]:
105    ///
106    /// **⚠️ The following code is in c ⚠️**
107    ///
108    /// ```c
109    /// JsonParser *parser = json_parser_new ();
110    /// json_parser_load_from_data (parser, json_data, -1, NULL);
111    /// ```
112    ///
113    /// If we run the following code:
114    ///
115    /// **⚠️ The following code is in c ⚠️**
116    ///
117    /// ```c
118    /// JsonNode *result;
119    /// JsonPath *path = json_path_new ();
120    /// json_path_compile (path, "$.store..author", NULL);
121    /// result = json_path_match (path, json_parser_get_root (parser));
122    /// ```
123    ///
124    /// The `result` node will contain an array with all values of the
125    /// author member of the objects in the JSON tree. If we use a
126    /// [`Generator`][crate::Generator] to convert the `result` node to a string
127    /// and print it:
128    ///
129    /// **⚠️ The following code is in c ⚠️**
130    ///
131    /// ```c
132    /// JsonGenerator *generator = json_generator_new ();
133    /// json_generator_set_root (generator, result);
134    /// char *str = json_generator_to_data (generator, NULL);
135    /// g_print ("Results: %s\n", str);
136    /// ```
137    ///
138    /// The output will be:
139    ///
140    /// ```json
141    /// ["Nigel Rees","Evelyn Waugh","Herman Melville","J. R. R. Tolkien"]
142    /// ```
143    ///
144    /// # Implements
145    ///
146    /// [`trait@glib::ObjectExt`]
147    #[doc(alias = "JsonPath")]
148    pub struct Path(Object<ffi::JsonPath, ffi::JsonPathClass>);
149
150    match fn {
151        type_ => || ffi::json_path_get_type(),
152    }
153}
154
155impl Path {
156    /// Creates a new `JsonPath` instance.
157    ///
158    /// Once created, the `JsonPath` object should be used with
159    /// [`compile()`][Self::compile()] and [`match_()`][Self::match_()].
160    ///
161    /// # Returns
162    ///
163    /// the newly created path
164    #[doc(alias = "json_path_new")]
165    pub fn new() -> Path {
166        assert_initialized_main_thread!();
167        unsafe { from_glib_full(ffi::json_path_new()) }
168    }
169
170    /// Validates and decomposes the given expression.
171    ///
172    /// A JSONPath expression must be compiled before calling
173    /// [`match_()`][Self::match_()].
174    /// ## `expression`
175    /// a JSONPath expression
176    ///
177    /// # Returns
178    ///
179    /// `TRUE` if the compilation was successful, and `FALSE`
180    ///   otherwise
181    #[doc(alias = "json_path_compile")]
182    pub fn compile(&self, expression: &str) -> Result<(), glib::Error> {
183        unsafe {
184            let mut error = std::ptr::null_mut();
185            let is_ok = ffi::json_path_compile(
186                self.to_glib_none().0,
187                expression.to_glib_none().0,
188                &mut error,
189            );
190            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
191            if error.is_null() {
192                Ok(())
193            } else {
194                Err(from_glib_full(error))
195            }
196        }
197    }
198
199    /// Matches the JSON tree pointed by `root` using the expression compiled
200    /// into the `JsonPath`.
201    ///
202    /// The nodes matching the expression will be copied into an array.
203    /// ## `root`
204    /// the root node of the JSON data to match
205    ///
206    /// # Returns
207    ///
208    /// a newly-created node of type
209    ///   `JSON_NODE_ARRAY` containing the array of matching nodes
210    #[doc(alias = "json_path_match")]
211    #[doc(alias = "match")]
212    pub fn match_(&self, root: &Node) -> Node {
213        unsafe {
214            from_glib_full(ffi::json_path_match(
215                self.to_glib_none().0,
216                root.to_glib_none().0,
217            ))
218        }
219    }
220
221    /// Queries a JSON tree using a JSONPath expression.
222    ///
223    /// This function is a simple wrapper around [`new()`][Self::new()],
224    /// [`compile()`][Self::compile()], and [`match_()`][Self::match_()]. It implicitly
225    /// creates a `JsonPath` instance, compiles the given expression and matches
226    /// it against the JSON tree pointed by `root`.
227    /// ## `expression`
228    /// a JSONPath expression
229    /// ## `root`
230    /// the root of a JSON tree
231    ///
232    /// # Returns
233    ///
234    /// a newly-created node of type
235    ///   `JSON_NODE_ARRAY` containing the array of matching nodes
236    #[doc(alias = "json_path_query")]
237    pub fn query(expression: &str, root: &Node) -> Result<Node, glib::Error> {
238        assert_initialized_main_thread!();
239        unsafe {
240            let mut error = std::ptr::null_mut();
241            let ret = ffi::json_path_query(
242                expression.to_glib_none().0,
243                root.to_glib_none().0,
244                &mut error,
245            );
246            if error.is_null() {
247                Ok(from_glib_full(ret))
248            } else {
249                Err(from_glib_full(error))
250            }
251        }
252    }
253}
254
255impl Default for Path {
256    fn default() -> Self {
257        Self::new()
258    }
259}