0

The following is the format of data that I need to parse in bash. Assuming that a bash variable holds this data, I need to be able to extract the value in xyz. Further, I need to be able to also extract aa and bb individually from with xyz.

"params": {
    "children": [
           {
                "abc": {
                    "pp": "1234567890",
                    "qq": "a.b.c"
                },
                "xyz": {
                    "aa": "0987654321",
                    "bb": "c.b.a"
                },
                "def": "p.q.r"
            }
        ],
        "def": "e.f.g.h"
    }

Any help on this is appreciated!

4
  • 7
    Use a JSON parser, please. Commented Dec 2, 2013 at 10:20
  • stedolan.github.io/jq Commented Dec 2, 2013 at 10:22
  • @devnull/@slayedbylucifer: I'm familiarizing myself with the json parsers. Thanks for the suggestion! Commented Dec 4, 2013 at 8:22
  • Possible duplicate Commented Dec 5, 2013 at 15:12

1 Answer 1

1

The shell is not a good language for writing general parsers. That said, if your input format is more or less exactly as shown, with maximally one "name": "value" pair per line, try this:

$ eval $(sed -n 's/"\([^"]*\)"[ :]*"\([^"]*\)".*/\1=\2/p' inputfile)
$ echo $aa
0987654321
$ echo $bb
c.b.a
Sign up to request clarification or add additional context in comments.

2 Comments

What if I have 'aa' and 'bb' under both 'abc' and 'xyz'? How would I retrieve a specific line?
Then I suggest using a tool matching the problem, i.e. a proper parser, which the shell isn't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.