Loading TOC...

MarkLogic 12 EA 1 Product Documentation
xdmp:from-json-string

xdmp:from-json-string(
   $arg as xs:string
) as item()*

Summary

Parses a string as JSON, returning an item sequence.

Parameters
arg JSON input to be parsed.

Usage Notes

A JSON object or string is parsed as a json:object.

The JSON null value is represented as the empty sequence, and serializes in a way that indicates it is a null value. Therefore, when the null value is returned to JSON via xdmp:to-json, the null value is preserved.

Nested arrays in JSON are turned into nested sets of json:arrays.

Any codepoints in the JSON string that aren't allowed in XML are rejected and an error is thrown.

Example

xdmp:from-json-string('["a", null, false]')
=>
json:array(
<json:array xmlns:xs="http://www.w3.org/2001/XMLSchema"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:json="http://marklogic.com/xdmp/json">
   <json:value xsi:type="xs:string">a</json:value>
   <json:value xsi:nil="true"/>
   <json:value xsi:type="xs:boolean">false</json:value>
</json:array>)
  

Example

xquery version "1.0-ml";

let $json :=
  '[{"some-key":45683}, "this is a string", 123]'
return
xdmp:from-json-string($json)

=>

json:array(
<json:array xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:json="http://marklogic.com/xdmp/json">
  <json:value>
    <json:object>
      <json:entry key="some-key">
        <json:value xsi:type="xs:integer">45683</json:value>
      </json:entry>
    </json:object>
  </json:value>
  <json:value xsi:type="xs:string">this is a string</json:value>
  <json:value xsi:type="xs:integer">123</json:value></json:array>)

Note that what is shown above is the serialization of the XQuery items to
a json:array.  You can also use some or all of the items in the XQuery data
model.  For example, consider the following, which adds to the map based on the
other values:

xquery version "1.0-ml";
let $json :=
  '[{"some-key":45683}, "this is a string", 123]'
let $items := xdmp:from-json-string($json)
let $put := map:put($items[1], xs:string($items[3]), $items[2])
return
($items[1], xdmp:to-json-string($items[1]))

(: returns the following json:array and JSON string:
json:object(
<json:object xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:json="http://marklogic.com/xdmp/json">
  <entry key="some-key">
    <json:value xsi:type="xs:integer">45683</json:value>
  </entry>
  <entry key="123">
    <json:value xsi:type="xs:string">this is a string</json:value>
  </entry>
</json:object>)
{"some-key":45683, "123":"this is a string"}

This query uses the map functions to modify the first json:object
in the json:array.
:)

Stack Overflow iconStack Overflow: Get the most useful answers to questions from the MarkLogic community, or ask your own question.