简体   繁体   English

在 JQ 中为值分配键

[英]assigning keys to values in JQ

Is there a way in jq to go from this stdout: jq 中有没有办法从这个标准输出中走出来:

Thu Jun 9 10:09:14 AM EDT 2022IP86.75.30.9

to this?:对此?:

{
    "date": "Thu Jun 9 10:09:14 AM EDT 2022",
    "ip": "86.75.30.9"
}

I was able to get part of the way there我能够到达那里的一部分

with this:有了这个:

echo $(date)IP$(myip.sh) | jq -R 'split("IP")'

that outputs this:输出这个:

[
  "Thu Jun 9 10:09:14 AM EDT 2022",
  "86.75.30.9"
]

thanks!!谢谢!!

You can create an object with the date and ip key in which you'll assign the first and second index accordingly:您可以使用dateip键创建一个对象,您将在其中相应地分配第一个和第二个索引:

split("IP") | { date: .[0], ip: .[1] }

Will produce会产生

{
  "date": "Thu Jun 9 10:09:14 AM EDT 2022",
  "ip": "86.75.30.9"
}

Online example在线示例

Using capture might come in handy:使用capture可能会派上用场:

jq -R 'capture("(?<date>.*)IP(?<ip>.*)")'
{
  "date": "Thu Jun 9 10:09:14 AM EDT 2022",
  "ip": "86.75.30.9"
}

Demo演示

Mixing with Shell Parameter Expansion :Shell 参数扩展混合:

line='Thu Jun 9 10:09:14 AM EDT 2022IP86.75.30.9'
jq -n --arg date "${line%IP*}" --arg ip "${line#*IP}" '$ARGS.named'
{
  "date": "Thu Jun 9 10:09:14 AM EDT 2022",
  "ip": "86.75.30.9"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM