Using a variable for the whole JSON string and building it piece wise can make the quoting less cumbersome and make the
curl command line more readable and easier to maintain even though the overall code is much more verbose.
Building the string is done here using the string self concatenation operator
+=. Note that in
json_string+=$name, for example, no quoting is necessary since there's no word splitting being performed and no special characters are present on the right hand side.
You can use an associative array to look up the value you want based on the provided key. Here I'm assigning the pairs individually. Below I'll show how to do them in one assignment.
declare -A sexes
curl -d "$json_string" " -H "Content-Type: application/json" -X POST http://localhost:8080/setacc
You can break the JSON up even more to make it look a little more structured in the code (the resulting string contents will still be a single-line string). Ideally, if you're using more complicated JSON than this you should use a purpose built JSON tool for building the structure.
Here's how you can make the associative array declaration and assignment all at once. The first example is on one line and the second is on multiple lines - again for improved readability and maintainability.
declare -A sexes='([female]="true" [male]="false")'
declare -A sexes='(