-1

Run

curl http://localhost:3000/

I will get an array output like this

[
  {
    "name": "name1",
    "wred": {
      "lsd": "8040baf7aded3319b0dec433b2461"
    },
    "node": "dfsafafafaf="
  },
  {
    "name": "name2",
    "wred": {
      "lsd": "e6b3a11581a800d"
    },
    "node": "fdsafzxcvx="
  },
  {
    "name": "name3",
    "wred": {
      "lsd": "d3319b0dec433b2461"
    },
    "node": "hlkkjjkhjas="
  }
]

I want to get name1 via Shell script

#!/bin/bash
get_name() {
  curl --silent "http://localhost:3000/" |
  grep '"name":' |
  sed -E 's/.*"([^"]+)".*/\1/'                                 
}
echo `get_name`

And I get result like this

name1 name2 name3

Please help me, many thanks.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Mark
  • 13
  • 5

1 Answers1

0

The output of the curl in JSON format. Use jq tool to extract. While technically you can process some JSON file with sed, this is risky: sed is line oriented, and JSON is structured. There is no guarantee that the JSON file will be formatted in a specific way.

curl ... | jq -r '.[0].name' 

Do 'man jq' to get full information. Short version: * The '.[0]' will select the first entry of the array * The 'name' select the name element * The '-r' produces 'raw' output - stripping the quotes.

dash-o
  • 13,723
  • 1
  • 10
  • 37