4

I have a following json file and I'm looking for a way to extract object using object path using bash shell.

For example, if I say extract('production-ap/ap-northeast-1'), then it will return me "accessKey": "OO", "accountID": "99".

I like bash shell scripting but have limited knowledge of it, please help!

Thanks

{
    "production-ap": {
        "ap-northeast-1": {
            "accessKey": "OO",
            "accountID": "99"
        },
        "ap-northeast-2": {
            "accessKey": "AB",
            "accountID": "12"
        }
    },
    "production-eu": {
        "eu-west-1": {
            "accessKey": "CD",
            "accountID": "34"
        },
        "us-east-1": {
            "accessKey": "CD",
            "accountID": "34"
        }
    },
    "production-us": {
        "us-east-1": {
            "accessKey": "EF",
            "accountID": "56"
        },
        "us-east-2": {
            "accessKey": "EF",
            "accountID": "56"
        }
    },
    "stage-ap": {
        "ap-northeast-1": {
            "accessKey": "AK",
            "accountID": "78"
        },
        "ap-northeast-2": {
            "accessKey": "AK",
            "accountID": "78"
        }
    },
    "stage-eu": {
        "eu-west-1": {
            "accessKey": "AK",
            "accountID": "55"
        },
        "eu-west-2": {
            "accessKey": "AK",
            "accountID": "55"
        }
    },
    "stage-us": {
        "us-east-1": {
            "accessKey": "AK",
            "accountID": "30"
        },
        "us-east-2": {
            "accessKey": "AK",
            "accountID": "30"
        }
    },
    "private": {
        "us-west-2": {
            "accessKey": "z2",
            "accountID": "52"
        },
        "us-west-1": {
            "accessKey": "z2",
            "accountID": "52"
        }
    }
}
4
  • How about this:stackoverflow.com/questions/1955505/… Commented Mar 11, 2014 at 4:56
  • @atupal, they all use python,... third party lib which my project requires no dependencies except bash shell Commented Mar 11, 2014 at 4:58
  • No, the jsawk uses only bash. Commented Mar 11, 2014 at 5:04
  • Jq would be helpful stedolan.github.io/jq Commented Mar 11, 2014 at 5:10

1 Answer 1

4

It's going to be flaky doing this using bash. There do seem to be json parsers written as shell scripts although I'm not sure how solid they are. I'd recommend something like jq which can run as a separate program and be used in a pipe. It's a standalone executable and written in C. There's no reason it can't be shipped along with your program.

Sign up to request clarification or add additional context in comments.

2 Comments

look like JSON.sh you suggested works as expected. I'm testing it more.
I took JSON.sh as the solution. It works very well. Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.