How to extract a json value substring with jq

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.

2

1 Answer

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like