chriskelly
chriskelly

Reputation: 7736

Return empty array when transforming xml data to json

I am returning some xml structure as json using the built-in MarkLogic json module. For the most part it does what I expect. However, when an element marked as an array is empty, it returns an empty string instead of an empty array. Here is an example:

xquery version "1.0-ml";

import module namespace json = "http://marklogic.com/xdmp/json"
at "/MarkLogic/json/json.xqy";

let $config := json:config("custom")
return (
  map:put( $config, "array-element-names", ("item") ),
  json:transform-to-json(<result>
    <item>21</item>
    <item>22</item>
    <item>23</item>
  </result>, $config),
  json:transform-to-json(<result></result>, $config))

Result:

{"result":{"item":["21", "22", "23"]}}
{"result":""}

I would expect an empty array if there were no items matching in the array-element-name called "item". i.e.

{"result":{"item":[]}}

Is there some way to configure it so it knows the element is required ?

Upvotes: 1

Views: 1066

Answers (1)

No - it will not create anything that is not there. In your case, what if the XML was more complex. There is no context of 'where' such an element might live - so it could not create it even if it wanted to.

Solution is to repair the content if needed by adding one element - or transforming it into the json-basic namespace - where those elements live inside of of an element noted as an array (which can be empty) - or third, use an XSD to hint to the processor what to do . But that would still need a containing element for the 'array' - and then the items would be minOccurance=0. But if this is the case, then repair and transform into the json/basic namespace is probably nice and simple for your example.

Upvotes: 4

Related Questions