The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,860 other subscribers

Jan-Piet Mens :: A shell command to create JSON: jo

Posted by jpluimers on 2023/08/30

Stumbled across something that goes well with jq (the sed for JSON of which I wrote about before), [Wayback/Archive] Jan-Piet Mens :: A shell command to create JSON: jo:

I got tired of attempting to get shell scripts to produce valid JSON. You’ve likely seen something like this before:

echo '{"name":"Jane"}'

It gets merrier if an element contains an environment variable: open double, close single, add variable, open single, blergh.

Enter jo:

$ jo name=Jane
{"name":"Jane"}

The idea occurred to me late at night, and I don’t know why this has taken so long to happen:

$ jo time=$(date +%s) dir=$HOME
{"time":1457195712,"dir":"/Users/jpm"}

Bam! Jo tries to be clever about types and knows null, booleans, strings and numbers. It does arrays, and it pretty-prints on demand:

$ jo -p -a spring summer winter
[
   "spring",
   "summer",
   "winter"
]

Inspired by [Wayback/Archive] a comment on HN, I added another hack: if a key’s value begins with an opening brace ({) or a bracket ([]) we attempt to decode JSON from it; this allows jo to add objects or arrays (use -a!) to itself. Watch:

$ jo -p name=JP object=$(jo fruit=Orange point=$(jo x=10 y=20) number=17) sunday=false
{
   "name": "JP",
   "object": {
      "fruit": "Orange",
      "point": {
         "x": 10,
         "y": 20
      },
      "number": 17
   },
   "sunday": false
}

jo also supports nested types natively:

$ jo -p number=17 pass=true geo[lon]=88 geo[cc]=ES point[]=1 point[]=2 geo[lat]=123.45
{
   "number": 17,
   "pass": true,
   "geo": {
      "lon": 88,
      "cc": "ES",
      "lat": 123.45
   },
   "point": [
      1,
      2
   ]
}

The git repository is at GitHub: [Wayback/Archive] jpmens/jo: JSON output from a shell.

I stumbled on it because of this Tweet by Daniel Stenberg, the cURL author:

[Archive] Daniel 🥌 Stenberg on Twitter: “jo | curl --json | jq In the future, you’ll forget there ever was a time when you didn’t use this trinity.” / Twitter

jo | curl --json | jq

In the future, you’ll forget there ever was a time when you didn’t use this trinity.

Of course it is not perfect (hey, it is software after all).

–jeroen


Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.