Search code examples
unixsedmacos-catalinadarwin

Using `sed` to remove all elements from JSON array


I know StackOverflow is not a code-writing-service, but sed has been driving me crazy for the past 3 hours.

In summary, I need to modify the contents of a .json file that I have.

What the file looks like:

{
// ...
    "first": {
        "second": [
            "indexZero",
            "theseStringsAreDynamic",
            "soINeedToUseWildcard"
        ]
    }
// ...
}

Desired result:

{
// ...
    "first": {
        "second": [
        ]
    }
// ...
}

What have you done?

I have tried about a million variations loosely based upon:

sed -i 's/\"second\": \[.*\]/\"second\": []/' "my.json"

## ~ Which gives: ~
#
#    "first": {
#        "second": []
#            "indexZero",
#            "theseStringsAreDynamic",
#            "soINeedToUseWildcard"
#        ]
#    },

Essentially, I need to remove all elements from an array in a .json file, so if sed is not the correct tool for the job, please let me know.

Thank you for your time.


Solution

  • The correct tool for the job is jq:

    $ jq '.first.second = []' input.json
    {
      "first": {
        "second": []
      }
    }
    

    To replace the original file, it's a two step process - redirect output to a temporary file and then rename it:

    jq '.first.second = []' orig.json > tmp.json && mv -f tmp.json orig.json