Search code examples
jsonbashsedshcut

Parse json response from curl using only bash without using jq or other tools


I have a curl command which returns a json response as

{
"customer_id": "9a081c0c",
"resources": ["credit-98797", "credit-98798", "loan-876", "loan-889-approved","loan-882-rejected", "loan-879-pending"],
"customer_info": "John",
"warnings": null
}

I am trying to create a script which would return the latest loan id, in this case loan-889-approved But having hard time getting it right.

I tried sorting all the loans and fetching the first element of the array, but I am doing it wrong

details=$(curl -u username:token https://1.2.3.4:8420/v1/customer/details/9a081c0c)
sortedLoans=$(for x in ${details[@]}; do if [["$x"=="loan"]]; then echo $x; fi done | sort ) 

And the main challenge is to doing it using only bash, without jq or json, if possible

I am new to shell scripting. Any advice is appreciated. Thanks in advance


Solution

  • Since you mention you cannot use jq, try this solution with grep+sort+tail

    curl '..' | grep -o 'loan-[^"]*' | sort -t- -k2n | tail -n1
    

    sort -t- -k2n will sort numerically based on number that is present after -