javascript - 在 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
解决方案
您面临的问题是因为您的$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
推荐阅读
- vba - VBA - WinHttpRequest.Send 进度
- python - Keras中的序列到序列自动编码器输入维度错误
- html - 定制手风琴的设计
- powershell - Import-Excel:前导零和结束行
- python - 如何将输入字段值转换为整数而不出错?
- html - XSLT 同级递归按列跨度,可以检测后续列区域是否被占用
- kubernetes - 如何在 Rancher kubernetes 中启用资源 EphemeralContainers
- javascript - 括号匹配的正则表达式
- spring-security - 来自尤里卡服务器的spring oauth2资源服务器jwt.jwk-set-uri
- scala - 如何读取压缩的 Spark eventLog?