How do I concatenate dummy values in JQ based on field value, and then CSV-aggregate these concatenations?

我的梦境 提交于 2021-01-29 15:28:20

问题


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'

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"}]

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:

  • all array objects (there could be more than 2 shown above) returned in a single comma-delimited row

  • doc fields are ignored

  • the values for "name" (including their surrounding double-quotes) are concatenated with either:
    • :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

Can someone show me how I can expand upon my initial jq to return this?

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"'

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 :)

Cheers,

Stan


回答1:


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'

With that JSON, the output would be:

{"id":1234567890,"test_string":"xxxxxxxxxx"}

However, it would be far better if you combined the three calls to jq into one.



来源:https://stackoverflow.com/questions/61964573/how-do-i-concatenate-dummy-values-in-jq-based-on-field-value-and-then-csv-aggre

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!