Home > Back-end >  assigning keys to values in JQ
assigning keys to values in JQ

Time:06-10

Is there a way in jq to go from this stdout:

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!!

CodePudding user response:

You can create an object with the date and ip key in which you'll assign the first and second index accordingly:

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

CodePudding user response:

Using capture might come in handy:

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

Demo

CodePudding user response:

Mixing with Shell Parameter Expansion:

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"
}
  • Related