2

I am trying to use a bash variable to store json.

  testConfig=",{
    \"Classification\": \"mapred-site\",
    \"Properties\": {
        \"mapreduce.map.java.opts\": \"-Xmx2270m\",
        \"mapreduce.map.memory.mb\": \"9712\"
      }
    }"

echo $testConfig Output: ,{

If I give it in a single line it works. But i would like to store values in my variable in a clean format.

I tried using cat >>ECHO That didn't work either

Any help is appreciated as to how I can store this in order to get the output in an expected format. Thanks.

dreddy
  • 463
  • 1
  • 7
  • 21
  • I think you can find the answer here : https://stackoverflow.com/questions/43373176/store-json-directly-in-bash-script-with-variables – Shuyuntake Apr 24 '18 at 14:35
  • [Security implications of forgetting to quote a variable in bash/POSIX shells](https://unix.stackexchange.com/questions/171346/security-implications-of-forgetting-to-quote-a-variable-in-bash-posix-shells) – glenn jackman Apr 24 '18 at 14:41
  • Cannot reproduce; the assignment is fine, and although you should quote the parameter expansion, that just preserves the newlines instead of replacing them with spaces. – chepner Apr 24 '18 at 14:42
  • 1
    In general, you should avoid trying to produce JSON by hand; let `jq` generate it for you. `testConfig=$(jq -n '{Classification: "mapred-site", Properties: { "mapreduce.map.java.opts": "-Xmx2270m", "mapreduce.map.memory.mb": "9712"}}')`. For hard-coded snippets like this, it doesn't matter, but it's very important if you start trying to generate dynamic JSON using parameters with unknown values (e.g., `{foo: "$bar"}`). – chepner Apr 24 '18 at 14:45
  • 2
    The fact that `testConfig` begins with a comma tells me you are building a larger JSON value using `testCongfig`, which makes the use of `jq` more important. – chepner Apr 24 '18 at 14:48

2 Answers2

2

You may use a here doc as described here:

read -r -d '' testConfig <<'EOF'
{
    "Classification": "mapred-site",
    "Properties": {
        "mapreduce.map.java.opts": "-Xmx2270m",
        "mapreduce.map.memory.mb": "9712"
      }
}
EOF

# Just to demonstrate that it works ...
echo "$testConfig" | jq .

Doing so you can avoid quoting.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
0

You can use read -d

read -d '' testConfig <<EOF
,{ /
        "Classification": "mapred-site", 
        "Properties": {/
            "mapreduce.map.java.opts": "-Xmx2270m", 
            "mapreduce.map.memory.mb": "9712"
          }
        }
EOF

echo $testConfig;
Chopi
  • 1,123
  • 1
  • 12
  • 23