Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq and Math functions

I'm retrieving JSON from a real estate database. jq makes it easy to pull out the separate properties/values, but some of the values are in inconvenient units. For example, the LotSize variable is in square feet (need to divide by 43560 to get acres, which is more conventional), and dateSold is a Linux timestamp. Here's a sample:

{
    "lotsize": 65340,
    "dateSold": 1207897200
} 

I'd like to be able to do math on values that jq processes. I've read the manual (https://stedolan.github.io/jq/manual/#Math) but it doesn't give me a sense of how to do it. I'd like to transform the JSON data above into something like this:

{
    "acres": 1.5,
    "soldOn": "Friday, April 11, 2008"
} 

I know I can patch this up Excel, but it'd be cool to have jq do it without any further processing. Any thoughts on doing this? Thanks.

like image 526
richb-hanover Avatar asked Nov 26 '18 01:11

richb-hanover


People also ask

What is jq used for?

jq is a lightweight and flexible command-line JSON processor. jq is like sed for JSON data – you can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep and friends let you play with text.

What is jq in statistics?

jq is a command-line tool like sed for JSON data and can be used to slice, filter, map, and transform structured data.

Is jq safe?

Is jq safe to use? The python package jq was scanned for known vulnerabilities and missing license, and no issues were found. Thus the package was deemed as safe to use.

What is jq slurp?

“Slurp” tells jq to read every line of the input JSON lines and treat the entire group as one huge array of objects. With the Twitter data still in the input box on jq play, check the “Slurp” box, and just put .


1 Answers

With your input,

jq -c '{acres: (.lotsize/43560), soldOn: (.dateSold | strftime("%A %B %d, %Y")) }'

produces:

{"acres":1.5,"soldOn":"Friday April 11, 2008"}

Recent versions of jq support the environment variable TZ so you might want to look at strflocaltime.

like image 58
peak Avatar answered Nov 04 '22 01:11

peak