3

I need set into variable true/false value and send him into json with curl command:

name=$1
sx=$2

`curl -d '{"name":"'"$name"'", "sex":true}' -H "Content-Type: application/json" -X POST http://localhost:8080/setacc`

Variable sx accepts the value male or female how to set the appropriate boolean value into sex variable?

3 Answers3

5

The easiest way to map the string male to either true or false (depending on your needs) and female to some other value is a simple if…then…else clause. The trick is the quoting but you already got that with the $name variable. So:

if [ "$sx" = "male" ]; then
    sex="true";     # or whatever you consider male sex to be
else
    sex="false";    # just the opposite, see above
fi

curl -d '{"name":"'"$name"'", "sex":'$sex'}' -H "Content-Type: application/json" -X POST http://localhost:8080/setacc
PerlDuck
  • 13,885
3

In your case you use json and can use text "true" and text "false".

You need add to bash script logic:

sex="false"
if [ "$sx" = "male" ]; then
  sex="true"
fi

then run curl command with ... {"name":"'"$name"'", "sex":\"$sex\"} ... or just ... {"name":"'"$name"'", "sex":$sex} ...

Test script:

#!/bin/bash

sx="male"

sex="false"
if [ "$sx" = "male" ]; then
  sex="true"
fi

echo \"$sex\"
slava
  • 4,085
2

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.

name=$1
sx=$2

declare -A sexes
sexes[male]=false
sexes[female]=true

json_string='{"name":"'
json_string+=$name
json_string+='", "sex":'
json_string+=${sexes[$sx]}
json_string+='}'

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='(
    [female]="true"
    [male]="false"
)'