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.

5
  • I think you can find the answer here : stackoverflow.com/questions/43373176/… Commented Apr 24, 2018 at 14:35
  • Security implications of forgetting to quote a variable in bash/POSIX shells Commented Apr 24, 2018 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. Commented Apr 24, 2018 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"}). Commented Apr 24, 2018 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. Commented Apr 24, 2018 at 14:48

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.