1

I am very new to bash scripting, please can someone point me in the right direction on how to accomplish my task? I have a curl call which returns a string, which I want to convert to json.

My curl statement -

curl --insecure -X POST 'https://url/api/IPAM/GetIP' --header 'Content-Type: application/json' --header -d '{"key1": "value1"}'

This curl statement returns a string ,for example: 10.100.100.100

I want to fetch this string and return the output in json format:

{"IP":"10.100.100.100"}

I don't want to use jquery or python to do this because this entire script will be run by a wrapper that only understands bash.

0

3 Answers 3

2

You can use jq to process your IP string into a JSON string and package it into a JSON object of your choice.

ip="10.100.100.100"
jq --arg ip "$ip" -cn '{"IP":$ip}'

Result:

{"IP":"10.100.100.100"}

Now if working with the result of your example curl POST request:

rawip_string=$(curl --insecure -X POST 'https://url/api/IPAM/GetIP' --header 'Content-Type: application/json' --header -d '{"key1": "value1"}')

jq --arg ip "$rawip_string" -cn '{"IP":$ip}'
Sign up to request clarification or add additional context in comments.

Comments

1

One way to not rely on external tools like jq, you can get the output ip attribute that to a variable and concatenate it.

$ return=$(echo 10.100.100.100)
$ echo "{\"IP\":\"${return}\"}"
{"IP":"10.100.100.100"}

2 Comments

printf '{"IP":"%s"}' "$return" is arguably cleaner and easier to read/debug. Although it only work if $return contains no control character or double-quote that would need escaping to make it a proper JSON string.
Oops didn't see this comment)
1

Like this

printf '{"IP":"%s"}' "$(curl --insecure -X POST 'https://url/api/IPAM/GetIP' --header 'Content-Type: application/json' --header -d '{"key1": "value1"}')"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.