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?
The easiest way to map the string
male
to eithertrue
orfalse
(depending on your needs) andfemale
to some other value is a simpleif…then…else
clause. The trick is the quoting but you already got that with the$name
variable. So:In your case you use json and can use text "true" and text "false".
You need add to bash script logic:
then run curl command with
... {"name":"'"$name"'", "sex":\"$sex\"} ...
or just... {"name":"'"$name"'", "sex":$sex} ...
Test script:
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 injson_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.
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.