Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

linux - How to parse json response in the shell script?

I am working with bash shell script. I need to execute an URL using shell script and then parse the json data coming from it.

This is my URL - http://localhost:8080/test_beat and the responses I can get after hitting the URL will be from either these two -

{"error": "error_message"}
{"success": "success_message"}

Below is my shell script which executes the URL using wget.

#!/bin/bash

DATA=$(wget -O - -q -t 1 http://localhost:8080/test_beat)
#grep $DATA for error and success key

Now I am not sure how to parse json response in $DATA and see whether the key is success or error. If the key is success, then I will print a message "success" and print $DATA value and exit out of the shell script with zero status code but if the key is error, then I will print "error" and print $DATA value and exit out of the shell script with non zero status code.

How can I parse json response and extract the key from it in shell script?

I don't want to install any library to do this since my JSON response is fixed and it will always be same as shown above so any simpler way is fine.

Update:-

Below is my final shell script -

#!/bin/bash

DATA=$(wget -O - -q -t 1 http://localhost:8080/tester)
echo $DATA
#grep $DATA for error and success key
IFS=" read __ KEY __ MESSAGE __ <<< "$DATA"
case "$KEY" in
success)
    exit 0
    ;;
error)
    exit 1
    ;;
esac    

Does this looks right?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you are going to be using any more complicated json from the shell and you can install additional software, jq is going to be your friend.

So, for example, if you want to just extract the error message if present, then you can do this:

$ echo '{"error": "Some Error"}' | jq ".error"
"Some Error"

If you try this on the success case, it will do:

$echo '{"success": "Yay"}' | jq ".error"
null

The main advantage of the tool is simply that it fully understands json. So, no need for concern over corner cases and whatnot.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...