使用 Bash shell 提取 JSON 对象? [英] Extract JSON object using Bash shell?

查看:29
本文介绍了使用 Bash shell 提取 JSON 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以下 json 文件,我正在寻找一种使用 bash shell 使用对象路径提取对象的方法.

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

例如,如果我说 extract('production-ap/ap-northeast-1'),那么它会返回我 "accessKey": "OO", "accountID": "99".

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

我喜欢 bash shell 脚本,但对它的了解有限,请帮助!

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

谢谢

{
    "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"
        }
    }
}

推荐答案

使用 bash 执行此操作会很不稳定.有 确实 json 解析器编写为 shell 脚本,尽管我不确定它们有多可靠.我推荐像 jq 这样的东西,它可以作为单独的程序运行并在管道中使用.它是一个独立的可执行文件,用 C 语言编写.没有理由不能与您的程序一起提供.

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.

这篇关于使用 Bash shell 提取 JSON 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆