How to extract a json value substring with jq
Asked Answered
R

1

9

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.

Request answered 25/8, 2019 at 21:9 Comment(2)
FYI, better to use <old.json than cat old.json. It's a small difference with jq, but with commands that benefit from being able to use seek() and tell() to read from different parts of a file, skip to the end, parallelize operations between threads, measure length in constant time, or do any of the other things one can do with a real file handle but can't do with a FIFO, the difference in performance can be huge.Newfeld
...for example, cat foo | wc -c will read foo all the way from the beginning, but <foo wc -c doesn't read any of the file's contents at all, but jumps straight to the end and performs a constant-time operation to request its current position. Similarly, GNU sort can parallelize sorting a huge file into subprocesses that each handle a subset and merge their results together -- but if it's given a pipeline to read from, then the process of reading input can't be parallelized at all!Newfeld
N
13

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

Newfeld answered 25/8, 2019 at 21:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.