JSONata Query

Command: jsonata

Description: Apply a JSONata expression to transform JSON data.

Arguments

Notes

JSONata is a query/transformation language that lets you turn a string of JSON into another string of JSON. It allows you to filter based on values, rename properties, extract elements from arrays, create aggregate values from multiple properties, etc.

JSONdata Documentation

That site also has a very handy resource for testing JSONata -- you can paste your JSON string in, and dynamically edit JSONata while seeing the immediate results.

JSONata Exerciser

This command is handy for simplifying JSON before making a table with it. In this example, an array of complex JSON objects is reduced to a simple object with clearer property names, which will become column names (using the header-regex argument, the underscores are replaced with spaces).

# Assume a big string of JSON is obtained here...

jsonata -expr:$jsonata
make-table -header-regex:"s/_/ /g"

$jsonata
data.{
    "Subject": settings.en_US.subject,
    "Date_Sent": sentAt,
    "Sent_By": sender.name & " <" & sender.emailAddress & ">"
}

Source Code

import jsonata from "jsonata";

async function jsonataQuery(working, command, p) {
  const expr = command.getArg("expr");

  const data = JSON.parse(working.text);

  let result;
  try {
    result = await jsonata(expr).evaluate(data);
  } catch (e) {
    throw new Error(`JSONata expression failed to evaluate: ${e.message}`);
  }

  return {
    text: JSON.stringify(result),
    contentType: "application/json",
  };
}

// Meta

jsonataQuery.title = "JSONata Query";
jsonataQuery.description = "Apply a JSONata expression to transform JSON data.";
jsonataQuery.args = [
  {
    name: "expr",
    type: "string",
    description: "JSONata expression to evaluate",
  },
];
jsonataQuery.allowedContentTypes = ["json"];
jsonataQuery.parseValidators = [
  {
    test: (command) => {
      return command.hasArg("expr");
    },
    message: "You must provide a JSONata expression.",
  },
];

export default jsonataQuery;