gron grep for JSON

2023-06-23 gron json grep jsonplaceholder

When I was playing with jq tool I noticed interesting tool named gron to allow easy filtering of JSON documents. It turns the JSON into sequence of assignments. There is an example provided in the tool documentation based on useful {JSON} Placeholder website

{
  "id": 1,
  "name": "Leanne Graham",
  "username": "Bret",
  "email": "Sincere@april.biz",
  "address": {
    "street": "Kulas Light",
    "suite": "Apt. 556",
    "city": "Gwenborough",
    "zipcode": "92998-3874",
    "geo": {
      "lat": "-37.3159",
      "lng": "81.1496"
    }
  },
  "phone": "1-770-736-8031 x56442",
  "website": "hildegard.org",
  "company": {
    "name": "Romaguera-Crona",
    "catchPhrase": "Multi-layered client-server neural-net",
    "bs": "harness real-time e-markets"
  }
}

gron turns it into this

json = {};        
json.address = {};
json.address.city = "Gwenborough";
json.address.geo = {};
json.address.geo.lat = "-37.3159";
json.address.geo.lng = "81.1496";
json.address.street = "Kulas Light";
json.address.suite = "Apt. 556";
json.address.zipcode = "92998-3874";
json.company = {};
json.company.bs = "harness real-time e-markets";
json.company.catchPhrase = "Multi-layered client-server neural-net";
json.company.name = "Romaguera-Crona";
json.email = "Sincere@april.biz";
json.id = 1;
json.name = "Leanne Graham";
json.phone = "1-770-736-8031 x56442";
json.username = "Bret";
json.website = "hildegard.org";

As each line stands of its own and contains both the structure and values, it makes it easy to use line filters to pick just some of the data

gron http://jsonplaceholder.typicode.com/users/1 | grep company

produces

json.company = {};
json.company.bs = "harness real-time e-markets";
json.company.catchPhrase = "Multi-layered client-server neural-net";
json.company.name = "Romaguera-Crona";

Such output can be constructed back into the JSON with gron --ungron or gron -u

gron http://jsonplaceholder.typicode.com/users/1 | grep company | gron -u

builds this

{
  "company": {
    "bs": "harness real-time e-markets",
    "catchPhrase": "Multi-layered client-server neural-net",
    "name": "Romaguera-Crona"
  }
}

I like the approach that simple transformation will allow many tools from Unix ecosystem to work with structured data. The example above shows just filtering, but the program in the middle can also transform the assignments and change values or restructure the file.