Hacker News new | ask | show | jobs
by stickfigure 933 days ago
Congratulations! We're almost back to the basic functionality we used to have with XSLT.
3 comments

You could use an elaborate filter with jq (see https://stackoverflow.com/a/73040814/452614) to transform JSON to XML and then use an XQuery implementation to process the document. It would be quite powerful, especially if the implementation supports XML Schema. I have not tested it.

Or https://github.com/AtomGraph/JSON2XML which is based on https://www.w3.org/TR/xslt-30/#json-to-xml-mapping

It even looks like we could use an XSLT 3 processor with the json-to-xml function (https://www.w3.org/TR/xslt-30/#func-json-to-xml) and then use XQuery or stay with XSLT 3.

Now I have to test it.

In fact XQuery alone is enough, e.g. with Saxon HE 12.3.

    (: file json2xml.xq :)
    declare default element namespace "http://www.w3.org/2005/xpath-functions";
    declare option saxon:output "method=text";
    declare variable $file as xs:string external;
    json-to-xml(unparsed-text($file))/<your xpath goes here>

    java -cp ~/Java/SaxonHE12-3J/saxon-he-12.3.jar net.sf.saxon.Query -q:json2xml.xq file='/path/to/file.json'
To be fair, xslt is a lot more verbose than `map(.*2)`
A bit more verbose but you have the full power of XQuery with you. XSLT however is more verbose than that like you mentioned.

    for $price in json-to-xml(unparsed-text($file))/map/map/number[@key="price"]
    return $price+2
For the following JSON document:

    {
      "fruit1": {
        "name": "apple",
        "color": "green",
        "price": 1.2
      },
      "fruit2": {
        "name": "pear",
        "color": "green",
        "price": 1.6
      }
    }
The call to json-to-xml() produces this XML document:

    <?xml version="1.0" encoding="UTF-8"?>
    <map xmlns="http://www.w3.org/2005/xpath-functions">
       <map key="fruit1">
          <string key="name">apple</string>
          <string key="color">green</string>
          <number key="price">1.2</number>
       </map>
       <map key="fruit2">
          <string key="name">pear</string>
          <string key="color">green</string>
          <number key="price">1.6</number>
       </map>
    </map>
Yes. jq is essentially an XPath/XSLT for JSON. I'd say that jq is more powerful than XPath/XSLT, but that's neither here nor there since both can evolve to be as powerful as they need to be.