如何使用 JSONata 更改 JSON 响应

Jon*_*ght 1 jsonata

我正在使用返回以下 JSON 的 API:

{
  "rows": [
    {
      "keys": [
        "search term 1",
        "https://example.com/article-about-keyword-1/"
      ],
      "clicks": 24,
      "impressions": 54,
      "ctr": 0.4444444444444444,
      "position": 2.037037037037037
    },
    {
      "keys": [
        "search term 2",
        "https://example.com/article-about-keyword-2/"
      ],
      "clicks": 17,
      "impressions": 107,
      "ctr": 0.1588785046728972,
      "position": 2.663551401869159
    }
],
  "responseAggregationType": "byPage"
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用 JSONata 将其更改为更像这样的内容:

 {
  "rows": [
    {
      "keyword": search term 1,
      "URL": https://example.com/article-about-keyword-1/,
      "clicks": 24,
      "impressions": 54,
      "ctr": 0.4444444444444444,
      "position": 2.037037037037037
    },
    {
      "keyword": search term 2,
      "URL": https://example.com/article-about-keyword-2/,
      "clicks": 17,
      "impressions": 107,
      "ctr": 0.1588785046728972,
      "position": 2.663551401869159
    }
],
  "responseAggregationType": "byPage"
}
Run Code Online (Sandbox Code Playgroud)

基本上,我正在尝试将“键”部分分解为“关键字”和“URL”。

已经在https://try.jsonata.org/玩了一段时间,但我还没有走得太远。任何帮助表示赞赏。

Raf*_*ski 8

拆分键数组应该可以通过按索引访问每个元素来实现(假设关键字和 URL 保证出现在同一索引上)。

\n

这里\xe2\x80\x99s 是从源文件转换为所需目标形状的完整 JSONata 表达式:

\n
{\n  "rows": rows.{\n    "keyword": keys[0],\n    "URL": keys[1],\n    "clicks": clicks,\n    "impressions": impressions,\n    "ctr": ctr,\n    "position": position \n  }[],\n  "responseAggregationType": responseAggregationType\n}\n
Run Code Online (Sandbox Code Playgroud)\n

顺便说一句,我\xe2\x80\x99 使用我的团队在 Stedi 构建的映射工具在 2 分钟内构建了这个解决方案。

\n

映射用户界面

\n