使用Bash shell如何提取JSON对象?

4
我有一个JSON文件,想要使用bash shell提取对象路径中的对象。比如说,如果我说extract('production-ap/ap-northeast-1'),那么它将返回"accessKey": "OO""accountID": "99"
我喜欢bash shell脚本,但了解有限,请帮忙!
感谢。
{
    "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"
        }
    }
}

这个怎么样:https://dev59.com/3HI-5IYBdhLWcg3wO1vl - atupal
@atupal,他们都使用Python,...第三方库,而我的项目除了Bash shell之外不需要任何依赖。 - Nam Nguyen
不,jsawk 只使用 bash。 - atupal
Jq会很有帮助 http://stedolan.github.io/jq/ - Girish
1个回答

4

使用bash来完成这个任务可能会不太可靠。虽然有一些用shell脚本编写的json解析器,但我不确定它们的稳定性如何。我建议使用像jq这样的东西,它可以作为一个独立的程序运行并在管道中使用。它是一个独立的可执行文件,用C语言编写。没有理由不能将它与您的程序一起打包。


看起来像你建议的 JSON.sh 工具运行正常。我正在进行更多的测试。 - Nam Nguyen
我选择了JSON.sh作为解决方案。它运行得非常好。谢谢。 - Nam Nguyen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接