0

the following parameter include list values ( list of machines ) for example

echo $list_of_machine

worker01.sys645.com worker02.sys645.com worker03.sys645.com worker04.sys645.com worker05.sys645.com

we have this standard json

{
  "MNN_server": [
    "master02.sys645.com"
  ],
  "HTTP_SERVER": [
    "master01.sys645.com",
  ]
}

how to append the values - $list_of_machine under HTTP_SERVER element , as the following

expected results

{
  "MNN_server": [
    "master02.sys645.com"
  ],
  "HTTP_SERVER": [
    "master01.sys645.com",
    "worker01.sys645.com",
    "worker02.sys645.com",
    "worker03.sys645.com",
    "worker04.sys645.com",
    "worker05.sys645.com"
  ]
}
2

Note that your "standard JSON" isn't actually JSON (there's an extra comma before the closing ] in HTTP_SERVER).

Also, sed will only work if the source is formatted in the way you need it, it won't work for arbitrary JSON (which may not have line breaks).

So a better solution is to use jq, as in

$ jq --arg list "$list_of_machine" '.HTTP_SERVER|=.+($list|split(" "))' < your_file.json 
{
  "MNN_server": [
    "master02.sys645.com"
  ],
  "HTTP_SERVER": [
    "master01.sys645.com",
    "worker01.sys645.com",
    "worker02.sys645.com",
    "worker03.sys645.com",
    "worker04.sys645.com",
    "worker05.sys645.com"
  ]
}

with a well-formed your_file.json, of course.

1

With slightly different indentation.

$ sed 's/\("master01.sys645.com",\)/\1'$(echo -e "\\\\n\\\\t\"${list_of_machine// /\",\\\\n\\\\t\"}\"")'/' json
{
  "MNN_server": [
    "master02.sys645.com"
  ],
  "HTTP_SERVER": [
    "master01.sys645.com",
        "worker01.sys645.com",
        "worker02.sys645.com",
        "worker03.sys645.com",
        "worker04.sys645.com",
        "worker05.sys645.com"
  ]
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.