0

I have a variable with an example JSON format, a mix of array and objects. I am trying to get the value for one of the objects in an array, without " or ,

Using only the basic grep command, for read-only servers. Please note that the server has only bash, doesn't have X code, and has no way to install jq or homebrew.

usage: grep [-abcdDEFGHhIiJLlMmnOopqRSsUVvwXxZz] [-A num] [-B num] [-C[num]]
        [-e pattern] [-f file] [--binary-files=value] [--color=when]
        [--context[=num]] [--directories=action] [--label] [--line-buffered]
        [--null] [pattern] [file ...]
echo $exampleJSON

Output:
{
  "array": [
    {
       "ex1": 901,
       "ex2": 902,
       "ex3": 903,
       "ex4": 904,
       "ex5": 905,
       "ex6": 906,
    }
  ]
  "something_else": {
    "a1": 0
  }
}

The closest I have gotten is with echo $exampleJSON | grep -Eo '"ex3":.*?[^\\],"' which will output:

"ex3": 903,"

How can I clean up and extract 903, assuming the value can change, please advise!

Wi R-01
  • 1
  • 2
  • 2
    Don't. It's the wrong tool for the job. – Charles Duffy Feb 13 '23 at 20:36
  • Does your server _really_ not have Python installed? That's very rare these days. – Charles Duffy Feb 13 '23 at 20:37
  • (You want `ex1` only when it exists in `array`, right? So if a new version of the file had `"extra_stuff": {"ex3": "something else here"}` you'd want to avoid that, right? That kind of contextual awareness isn't something regular expressions are suited for; they only parse [regular languages](https://en.wikipedia.org/wiki/Regular_language), and [JSON is not a regular language](https://cstheory.stackexchange.com/questions/3987/is-json-a-regular-language)). – Charles Duffy Feb 13 '23 at 20:38
  • Please post valid JSON. – Cyrus Feb 13 '23 at 20:38
  • The server doesn't have Python. What should I use if this particular server hasn't been worked on, and only contains the basic bash language? – Wi R-01 Feb 13 '23 at 20:45
  • GNU bash, version 3.2.57(1)-release – Wi R-01 Feb 13 '23 at 20:46

0 Answers0