-1

I have several files I have to clean. I want to apply them a jq filter to remove all keys who have an empty value. By empty I mean empty string, empty object and arrays with just one empty string inside.

input

{
  "foo": {
    "keep": "me",
    "remove": "",
    "nest": {
      "keep": "me",
      "remove": ""
    },
    "remove-me": {},
    "remove-me-to": [""]
  }
}

output

{
  "foo": {
    "keep": "me",
    "nest": {
      "keep": "me"
    }
  }
}

I have my working jq expression for this:

walk(if type == "object" then with_entries(select(.value | (. != {} and . != [""] and . != ""))) else . end)

But I didn't succed at rewriting the input file. My command is:

jq '. |= walk(if type == "object" then with_entries(select(.value | (. != {} and . != [""] and . != ""))) else . end)' test.json

I have a nice output from the terminal but the file is still the same.

Why the input file isn't updated?

Existe Deja
  • 1,227
  • 3
  • 14
  • 36
  • 2
    Here's a great reference for [in-place editing options](https://backreference.org/2011/01/29/in-place-editing-of-files/) – Joe Casadonte Jun 10 '21 at 10:26

1 Answers1

0

Solution is to use a tmp file.

I created the script clean.sh

#!/bin/sh

input=$1
tmp="tmp.json"
jq 'walk(if type == "object" then with_entries(select(.value | (. != {} and . != [""] and . != ""))) else . end)' $input > $tmp
mv $tmp $input

and then run

sh ./clean.sh input.json
Existe Deja
  • 1,227
  • 3
  • 14
  • 36