jq:将对象数组转换为对象 [英] jq: translate array of objects to object

查看:383
本文介绍了jq:将对象数组转换为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到curl的回复,格式如下:

I have a response from curl in a format like this:

[
  {
    "list": [
      {
        "value": 1,
        "id": 12
      },
      {
        "value": 15,
        "id": 13
      },
      {
        "value": -4,
        "id": 14
      }
    ]
  },
  ...
]

给出这样的ID之间的映射:

Given a mapping between ids like this:

{
  "12": "newId1",
  "13": "newId2",
  "14": "newId3"
}

我要这样做:

[
  {
    "list": {
      "newId1": 1,
      "newId2": 15,
      "newId3": -4,
    }
  },
  ...
]

这样我就得到了从ID到值的映射(并希望重新映射ID).

Such that I get a mapping from ids to values (and along the way I'd like to remap the ids).

我已经为此工作了一段时间,每次我都陷入僵局.

I've been working at this for a while and every time I get a deadend.

注意:如有必要,我可以使用Shell或类似工具执行循环.

Note: I can use Shell or the like to preform loops if necessary.

edit:这是我到目前为止开发的一个版本:

edit: Here's one version what I've developed so far:

jq '[].list.id = ($mapping.[] | select(.id == key)) | del(.id)' -M --argjson "mapping" "$mapping"

我认为这不是最好的版本,但是我正在寻找是否可以找到更接近我所需的旧版本.

I don't think it's the best one, but I'm looking to see if I can find an old version that was closer to what I need.

推荐答案

[当以下描述描述(a)如下所示的映射,以及(b)输入数据具有表格:

[ The following response was in answer to the question when it described (a) the mapping as shown below, and (b) the input data as having the form:

[
  {
    "list": [
      {
        "value": 1,
        "id1": 12
      },
      {
        "value": 15,
        "id2": 13
      },
      {
        "value": -4,
        "id3": 14
      }
    ]
  }
]

编辑结束]

在下面,我将假定可以通过以下函数使用该映射,但这是一个无关紧要的假设:

In the following I'll assume that the mapping is available via the following function, but that is an inessential assumption:

def mapping: {
  "id1": "newId1",
  "id2": "newId2",
  "id3": "newId3"
} ;

然后,以下jq过滤器将产生所需的输出:

The following jq filter will then produce the desired output:

map( .list
     |= (map( to_entries[]
              | (mapping[.key]) as $mapped
              | select($mapped)
              | {($mapped|tostring): .value} )
         | add) )

这篇关于jq:将对象数组转换为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆