Search code examples
javascriptnode.jsjsonjsonata

Jsonata v2.0.0 unexpected output


Latest JSONata 2.0.0 version gives [Object Promise] as output when run even on the browser without any async functions. Following is the example from the JSONata website.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>JSONata test</title>
    <script src="https://cdn.jsdelivr.net/npm/jsonata/jsonata.min.js"></script>
    <script>
      function greeting() {
        var json = JSON.parse(document.getElementById('json').value);
        var result = jsonata('"Hello, " & name').evaluate(json);
        document.getElementById('greeting').innerHTML = result;
      }
    </script>
  </head>
  <body>
    <textarea id="json">{ "name": "Wilbur" }</textarea>
    <button onclick="greeting()">Click me</button>
    <p id="greeting"></p>
  </body>
</html>

Why does this happen? I'm currently using v1.8.0 as it doesn't have this issue.


Solution

  • The JSONata team switched the JSONata evaluator to async functions rather than generators. This 2.0.0 release introduced a breaking change to the Javascript API, but no breaking changes to the JSONata language. (release notes)

    From the description on the Github pull request that necessitated the bump to 2 of the major version (incompatible version):

    Apart from allowing non-blocking/asynchronous functions - fetch(), fs.readFile etc. to run in parallel, there are additional benefits of switching to async/await - performance benefits.

    Per the documentation, the JSONata v2.0.0 API is now:

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8">
        <title>JSONata test</title>
        <script src="https://cdn.jsdelivr.net/npm/jsonata/jsonata.min.js"></script>
        <script>
          // `async`
          async function greeting() {
            var json = JSON.parse(document.getElementById('json').value);
            // `await`
            var result = await jsonata('"Hello, " & name').evaluate(json);
            document.getElementById('greeting').innerHTML = result;
          }
        </script>
      </head>
      <body>
        <textarea id="json">{ "name": "Wilbur" }</textarea>
        <button onclick="greeting()">Click me</button>
        <p id="greeting"></p>
      </body>
    </html>