json 用jq从字符串列表开始创建对象

mklgxw1f  于 2023-05-23  发布在  其他
关注(0)|答案(2)|浏览(256)

我想创建一个JSON对象,以JSON格式的字符串列表开始,如下所示

[
  "nonprod/global/app/sit01",
  "nonprod/global/app/dev02",
  "prod/na/app/prod01",
  "test/eu/app/cust01",
  "nonprod/global/app/dev03"
]

我想得到的是一个字符串列表的Map,它将列表中字符串的前两个单词作为键,并将以该特定键开头的字符串作为值。
我尝试了以下方法:

jq 'reduce (.[] | capture("(?<env_type>([^/]*/[^/]*))").env_type as $key | {($key) : [.]}) as $item ({}; . *= $item)'

并获得:

{
  "nonprod/global": [
    "nonprod/global/app/dev03"
  ],
  "prod/na": [
    "prod/na/app/prod01"
  ],
  "test/eu": [
    "test/eu/app/cust01"
  ],
  "prod/eu": [
    "prod/eu/app/prod01"
  ]
}

我期待:

{
  "nonprod/global":[
    "nonprod/global/app/sit01",
    "nonprod/global/app/dev02",
    "nonprod/global/app/dev03"
  ],
  "prod/eu":[
    "prod/eu/app/prod01"
  ],
  
  "prod/na":[
    "prod/na/app/prod01"
  ],
  "test/eu":[
    "test/eu/app/cust01"
  ]
}
yebdmbv4

yebdmbv41#

使用+=添加到数组。如果键不存在,jq将动态创建它(null + []计算为[]):

reduce (.[] | capture("^(?<env>(?<type>[^/]*/[^/]*).*)$")) as {$env, $type} 
({}; .[$type] += [$env])
{
  "nonprod/global": [
    "nonprod/global/app/sit01",
    "nonprod/global/app/dev02",
    "nonprod/global/app/dev03"
  ],
  "prod/na": [
    "prod/na/app/prod01"
  ],
  "test/eu": [
    "test/eu/app/cust01"
  ]
}

Demo

4urapxun

4urapxun2#

它的前两个词是关键词
你可以def输入一个在第二个斜杠处分割的函数,然后用它来group_by输入数组,创建一个数组的数组,然后用INDEX把它变成一个对象,对first项使用相同的函数。

def f: .[:indices("/")[1]];
group_by(f) | INDEX(first | f)
{
  "nonprod/global": [
    "nonprod/global/app/sit01",
    "nonprod/global/app/dev02",
    "nonprod/global/app/dev03"
  ],
  "prod/na": [
    "prod/na/app/prod01"
  ],
  "test/eu": [
    "test/eu/app/cust01"
  ]
}

Demo

相关问题