1

I have the below JSON file test.json

{
            "run_list": ["recipe[cookbook-ics-op::setup_server]"],
            "props": {
                "install_home": "/inst1",
                             "tmp_dir": "/inst1/tmp",
                "user": "rven"
                }
}

From a shell script, I have to add 2 more properties under props. I don't want to read the existing contents first & then add to it. Can anyone help with how I can do this?

Newbie
  • 105
  • 1
  • 6
  • 12

2 Answers2

0

Use a JSON-aware tool such as jq. To add two properties, foo and bar:

jq '.props.foo="hello" | .props.bar="bye"' <in.json >out.json

If you want to use shell variables for the values:

foo=hello; bar=bye
jq --arg foo="$foo" \
   --arg bar="$bar" \
   '.props.foo=$foo | .props.bar=$bar' \
   <in.json >out.json

If you want to be able to specify both key and value with shell variables:

key=hello; val=world
jq --arg key="$key" \
   --arg val="$val" \
  '.props[$key]=$val' \
  <in.json >out.json
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
-1

Try sed:

sed -e 's/"props": {/"props": { "foo": "bar", "spam": "eggs",/' test.json

Result:

{
        "run_list": ["recipe[cookbook-ics-op::setup_server]"],
        "props": { "foo": "bar", "spam": "eggs",
            "install_home": "/inst1",
                         "tmp_dir": "/inst1/tmp",
            "user": "rven"
            }
}
Paulo Scardine
  • 73,447
  • 11
  • 124
  • 153
  • This only works if the formatting is very specific. What if `props` is starting empty, in which case the trailing comma would break the syntax? What if there's a newline rather than a space immediately after the `:`? What if one of the keys already exists? – Charles Duffy Nov 04 '15 at 20:27
  • Also, it'll do the wrong thing if there's another key named `props` somewhere else in the file. – Charles Duffy Nov 04 '15 at 20:28
  • @CharlesDuffy: you are not wrong, but the OP asked for something that works with **this** file, not for a bullet-proof solution. Let him judge if it is enough. – Paulo Scardine Nov 04 '15 at 20:29
  • Sure, but if the OP only needed something that worked with **exactly** this file, they could just build an output file by hand and have their script copy it over. :) – Charles Duffy Nov 04 '15 at 20:30
  • Again, you may be right, but I would ratter hear this from the OP's mouth. – Paulo Scardine Nov 04 '15 at 20:31
  • Our audience isn't just the OP -- we're building a canonical Q&A database here. Answers should be objectively good, and robustness is a part of that. – Charles Duffy Nov 04 '15 at 20:32
  • You are entitled to your opinion, like everybody else. That is why we have a voting system. – Paulo Scardine Nov 04 '15 at 20:36
  • And I'm entitled to try to encourage others to share that opinion, which is why we have a comment system. But, granted, we're at an impasse here, and I'll trouble you no more. – Charles Duffy Nov 04 '15 at 20:36