8

I have this json:

{"temperature":"21", "humidity":"12.3", "message":"Today ID 342 is running"}

I want to use jq to obtain this json:

{"temp":"21", "hum":"12.3", "id":"342"}

As you can see, what i want to do is extract the ID number 342 and put it in the new json with a different key name. I think i should use a regex but i don't know how to insert it in jq syntax.

I can create another json using the basic command:

cat old.json | jq '{temp:.temperature,hum:.humidity, id:.message}' > new.json

I know i can select substring using square brackets, but i don't want to use them because they don't take into account strings with different lengths and structure. I want to use a regex because i know that the ID number comes lways after the "ID" part.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
alcor
  • 515
  • 1
  • 8
  • 21

1 Answers1

12

You're right that a regex is the way to go here. Fortunately, the jq manual has a large section on using them.

jq '
{
  temp: .temperature,
  hum: .humidity,
  id: (.message | capture("ID (?<id>[[:digit:]]+)").id)
}' <old.json >new.json

You can see this running with your sample data at https://jqplay.org/s/k-ZylbOC6W

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441