0

I am writing a shell script to run some api's. It return response fine but i need some specific parameter to grep from the response and want to save in file. My script look like

#!/bin/sh
response=$(curl 'https://example.com' -H 'Content-Type: application/json' )
echo "$response" 

reponse is something like

{
status:"success",
response:{
   "target":"",
   "content":"test content"
}
}

Response is fine and i am able to write whole response in file but My requirement is to save only "content" inside "response" object using the script. which i need for another api. Note: I cannot change api responses as I am working third party api's;

Thank you

Teekay
  • 114
  • 5

3 Answers3

1

If the output is proper JSON:

$ cat proper.json
{
  "status": "success",
  "response": {
    "target": "",
    "content": "test content"
  }
}
$ response=$(cat proper.json)

You could use jq:

$ echo $response | jq -r '.response.content'
test content
James Brown
  • 36,089
  • 7
  • 43
  • 59
0

You can do this to get the value of contents into a variable ($content).

content=$(echo "$response" | cut -d'"' -f 7)

Explanation - Split the $response using " (double quote) as the delimiter and use the 7th field of the output (i.e the value (test content) of content in the json response)

Here is an excerpt from the description and usage of the cut command

if you like to extract a whole field, you can combine option -f and -d. The option -f specifies which field you want to extract, and the option -d specifies what is the field delimiter that is used in the input file.

DeadLock
  • 448
  • 3
  • 11
0

You can grep for the content and then use awk to split by : and take only the value, not the key

grep "\"content\":" | awk -F":" '{ print $2}' 

Will print "test content"

Robert D. Mogos
  • 900
  • 7
  • 14