Conversion Functions

2.3 The JSON Serialization Method

The JSON serialization process is also implemented in the serializer component of Zorba exposed through external C/C++ API. This is similar to using any of the serialization methods defined in the "XSLT 2.0 and XQuery 1.0 Serialization" specification at http://www.w3.org/TR/xslt-xquery-serialization/. This method can be triggered by the Zorba command line utility or by any of the Zorba programming APIs.

In the following three examples, we use the Zorba command line utility to serialize the result of a query and generate JSON by using the --serialization-parameter,-z option.

In contrast to the serialize function described above, the JSON serializer has to be passed a single element node adhering to the structure presented above (see conv_json). This is because a valid JSON document is required to have a single root object. If a query returns a sequence with more then one element, the API0066 error is raised (see appendix_converters and Example 3 below).

Example 1:

zorba -q "<json type='object'><pair name='firstName' type='string'>John</pair></json>" -z method=json

Result of Example 1:

{"firstName": "John"}

Example 2:

zorba -q "<ul>1</ul>" -z method=json

Output of Example 2:

[API0061] Could not serialize element with string representation {1}. Error: {This is not a Json element.}

Example 3

zorba -q "(<json type='object'><pair name='firstName' type='string'>John</pair></json>, 2)" -z method=json

Output of Example 3:

{"firstName": "John"}
[API0066] Cannot serialize a sequence if 'json' or 'jsonml' method was selected.

3.3 The JsonML Serialization Method

The JsonML serialization functionality is also implemented in the serializer component of Zorba.

In the following, we give some examples that demonstrate this using the zorba command line utility using the --serialization-parameter,-z option.
Please note that the result of query has to be a sequence with one element.

Here are some examples:

Note that is you pass a sequence of items, only the first item in the sequence will be processed and then an error is raised API0066 (see appendix_converters).
See example 3 below:

Example 1:

zorba -q "<ul>1</ul>" -z method=jsonml

Output of Example 1:

["ul", "1"]

Example 2

zorba -q "<?pi content?>" -z method=jsonml

Output of Example 2:

[API0064] Could not serialize element with string representation {content}. Error: {This is not a JsonML element.}

Example 3

zorba -q "(<ul>1</ul>, <?pi content?>)" -z method=jsonml

Output of Example 3:

["ul", "1"]
[API0066] Cannot serialize a sequence if 'json' or 'jsonml' method was selected.
 All Files