如何根据字段值在JQ中连接虚拟值,然后CSV聚合这些连接? [英] How do I concatenate dummy values in JQ based on field value, and then CSV-aggregate these concatenations?
问题描述
在我的bash脚本中,当我对curl结果运行以下jq时:
curl -u someKey:someSecret someURL 2>/dev/null | jq -r '.schema' | jq -r -c '.fields'
In my bash script, when I run the following jq against my curl result:
curl -u someKey:someSecret someURL 2>/dev/null | jq -r '.schema' | jq -r -c '.fields'
我返回一个JSON数组,如下所示:
[{"name":"id","type":"int","doc":"Documentation for the id field."},{"name":"test_string","type":"string","doc":"Documentation for the test_string field"}]
I get back a JSON array as follows:
[{"name":"id","type":"int","doc":"Documentation for the id field."},{"name":"test_string","type":"string","doc":"Documentation for the test_string field"}]
我的目标是应用jq进行调用以返回以下内容(鉴于上述示例):
{"id":1234567890,"test_string":"xxxxxxxxxx"}
NB:我正在尝试自动生成与上面显示的"schema" JSON相匹配的模板化值.
My goal is to do a call with jq applied to return the following (given the example above):
{"id":1234567890,"test_string":"xxxxxxxxxx"}
NB: I am trying to automatically generate templated values that match the "schema" JSON shown above.
因此,为了澄清一下,即:
So just to clarify, that is:
-
所有数组对象(上面显示的可能超过2个)都在一个逗号分隔的行中返回
all array objects (there could be more than 2 shown above) returned in a single comma-delimited row
doc字段被忽略
- :1234567890 ...当该对象的类型"为"int"时
- ":xxxxxxxxxx" ...当该对象的类型"为字符串"时
注意:这些将是我们目前唯一获得的类型
- :1234567890 ...when the "type" for that object is "int"
- ":xxxxxxxxxx" ...when the "type" for that object is "string"
NB: these will be the only types we ever get for now
有人可以告诉我如何扩展初始jq来返回此值吗?
注意:我尝试沿着以下路径工作,但超出此范围而失败...
curl -u someKey:someSecret someURL 2>/dev/null | jq -r '.schema' | jq -r -c '.fields' | "\(.name):xxxxxxxxxxx"'
NB: I tried working down the following path but am failing beyond this...
curl -u someKey:someSecret someURL 2>/dev/null | jq -r '.schema' | jq -r -c '.fields' | "\(.name):xxxxxxxxxxx"'
如果不可能使用纯JQ(我的偏爱),我也很高兴提供一种结合了sed/awk魔术的解决方案:)
If it's not possible in pure JQ (my preference) I'm also happy for a solution that mixes in a bit of sed/awk magic :)
干杯
斯坦
推荐答案
鉴于显示的JSON,您可以将以下内容添加到管道中:
Given the JSON shown, you could add the following to your pipeline:
jq -c 'map({(.name): (if .type == "int" then 1234567890 else "xxxxxxxxxx" end)})|add'
使用该JSON,输出将是:
With that JSON, the output would be:
{"id":1234567890,"test_string":"xxxxxxxxxx"}
但是,如果将对jq的三个调用合并为一个,那就更好了.
However, it would be far better if you combined the three calls to jq into one.
这篇关于如何根据字段值在JQ中连接虚拟值,然后CSV聚合这些连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!