jq and Math functions
Asked Answered
R

1

17

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.

Razz answered 26/11, 2018 at 1:6 Comment(0)
C
24

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.

Checkbook answered 26/11, 2018 at 2:34 Comment(1)
Perfect. Actually, I had forgotten that the time stamp was in milliseconds since the epoch. jq just allows filtered expressions, so I just used: ((.dateSold/1000) | strftime("%A %B %d, %Y"))Razz

© 2022 - 2024 — McMap. All rights reserved.