6

I have a JSON file I need to update a particular value.

{
  "Comment": "comment",
  "test": {
    "enabled": true
  },
  "enabled": true,
  "otherStuff": blah,
  "otherStuff2": blah,
  "otherStuff3": blah,
}

I would like to change the value of the second "enabled" to false. With JQ Parser, I can easily retrieve it with jq '.enabled', but I'm not sure what's the best way to manipulate the JSON.

The JSON is a respond i get from an API and may change in the future, I cannot rely on the line or value before/after.

Bastien974
  • 1,824
  • 12
  • 43
  • 61

2 Answers2

14

a quick experiment:

$ echo '{
  "Comment": "comment",
  "test": {
    "enabled": true
   },
  "enabled": true,
  "otherStuff": "blah",
  "otherStuff2": "blah",
  "otherStuff3": "blah"
}' |
jq '.enabled=false'
{
  "otherStuff3": "blah",
  "otherStuff2": "blah",
  "otherStuff": "blah",
  "enabled": false,
  "test": {
    "enabled": true
  },
  "Comment": "comment"
}
glenn jackman
  • 4,320
  • 16
  • 19
1

I read the question as "in the shell" and not necessarily as "using only bash builtins".

Try jsawk, which allows for manipulation and is scriptable, thought it relies on js as a dependency.

If all you want to do is read a (unique) key from the JSON response, you could (adapted from Brendan OConnor):

curl <destination> | grep -Po '"keyname":.*?[^\\]",'`
msanford
  • 1,427
  • 15
  • 27