首页 > 解决方案 > 在 UI 中输入值和示例数据时使用 JSONata 获取动态输出

问题描述

我尝试将动态输入值传递给 JSONata,但它没有将其放入行中:15 我正在使用 $add(),在其中我正在为其分配输入值,但它不起作用。

<!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 query = document.getElementById("query").value;
        var expression = jsonata("$add()");
        expression.registerFunction("add", () => query);

        var result = expression.evaluate(json);
        document.getElementById("greeting").innerHTML = result;
      }
    </script>
  </head>
  <body>
    <textarea id="json">{ "name": "Wilbur" }</textarea>
    <textarea id="query">name</textarea>
    <button onclick="greeting()">Click me</button>
    <p id="greeting"></p>
  </body>
</html>

I am creating $add() function inside JSONata method and return dynamic input value but it is not giving desired output.

As of now I am getting whatever I am passing inside field but what I need is when I pass key for Ex:"name" I should get that value using jsonata expression. I need output same as what JSONata method returns

Let me know If I need to provide any other information

标签: javascriptjsonata

解决方案


您面临的问题是因为您的$add()函数被编写为返回查询本身,而不是查询的评估值。

需要在评估行上传递参数,并且函数的主体需要处理评估结果,例如:

// Change: Note the passing of the textbox query as a param
var expression = jsonata(`$add(${query})`); 
// Change: Using evaluated param as output
expression.registerFunction("add", (a) => `Hello ${a}!`);

您可以在文档的示例中registerFunction看到这一点:

var 表达式 = jsonata("$add(61, 10005)");
expression.registerFunction("add", (a, b) => a + b, "<nn:n>");

表达式.evaluate({}); // 10066

工作示例:https ://codepen.io/scarabaeus/pen/OJxJbXp?editors=1000


推荐阅读