Why parse JSON in command line
- for readable structuring data
- for easy understanding
- for efficacy less time
Solution
use jq, lightweight and flexible command-line JSON processor.
- Install jq
- Windows - via chocolatey
choco install jq or chocolatey install jq
- Linux / Unix Like
#Debian / Ubuntu base sudo apt-get update sudo apt-get install jq #RedHat / Fedora base sudo dnf update sudo dnf install jq
- Mac OS
brew update brew install jq
- Sample Use-Case
With curl example
- format json use js '.'
curl --location 'http://192.168.1.100/api/v4/projects/1/merge_requests/1/approvals' --header 'PRIVATE-TOKEN: <<YOUR TOKEN>>' | jq '.'
- Select property changes_count from json
NUM_MR_FILE=$(curl --location "$CI_API_V4_URL/projects/$CI_PROJECT_ID/merge_requests/$CI_MERGE_REQUEST_IID" --header "PRIVATE-TOKEN: $SECRET_GITLABINFO" | jq '.changes_count ') echo $NUM_MR_FILE
- Convert Field changes_count from string to number (jq tonumber)
NUM_MR_FILE=$(curl --location "$CI_API_V4_URL/projects/$CI_PROJECT_ID/merge_requests/$CI_MERGE_REQUEST_IID" --header "PRIVATE-TOKEN: $SECRET_GITLABINFO" | jq '.changes_count | tonumber ') echo $NUM_MR_FILE
- Select and Count from Array
NUM_APPROVE=$(curl --location "$CI_API_V4_URL/projects/$CI_PROJECT_ID/merge_requests/$CI_MERGE_REQUEST_IID/approvals" --header "PRIVATE-TOKEN: $SECRET_GITLABINFO" | jq '.approved_by | length') echo $NUM_APPROVE
Other Example Here jq Manual (development version) (jqlang.github.io)
Reference
Discover more from naiwaen@DebuggingSoft
Subscribe to get the latest posts sent to your email.