のぴぴのメモ

自分用のLinuxとかの技術メモ

JSONの文字列変換(JSON.dumps)をワンライナーのコマンド実行で実現する

コマンドでの作業で、pythonのコードを書くまででない場合の方法。
変数"POLICY"に設定したJSONを、pythonで文字列に変換して、変数"POLICY_ESCAPE"に格納する。

JSON→文字列にエンコード

やること

このJSONを、

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt1565607714000",
            "Effect": "Allow",
            "Action": [
                "iam:List*",
                "iam:PassRole"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}

これに変換します。

"{ \"Version\": \"2012-10-17\", \"Statement\": [ { \"Sid\": \"Stmt1565607714000\", \"Effect\": \"Allow\", \"Action\": [ \"iam:List*\", \"iam:PassRole\" ], \"Resource\": [ \"*\" ] } ] }\n"

コマンド

POLICY='{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt1565607714000",
            "Effect": "Allow",
            "Action": [
                "iam:List*",
                "iam:PassRole"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}'
POLICY_ESCAPE=$(echo ${POLICY} | python -c 'import json; import sys; print(json.dumps(sys.stdin.read()))')

文字列→JSONにデコード

上記の逆です。

POLICY_ESCAPE="{ \"Version\": \"2012-10-17\", \"Statement\": [ { \"Sid\": \"Stmt1565607714000\", \"Effect\": \"Allow\", \"Action\": [ \"iam:List*\", \"iam:PassRole\" ], \"Resource\": [ \"*\" ] } ] }\n"

POLICY=$(echo ${POLICY_ESCAPE} | python -c 'import json; import sys; str=sys.stdin.read(); dic=json.loads(str.replace("\\n","")); print("{}".format(json.dumps(dic,indent=4)))' )

実行結果

$ echo $POLICY
{ "Version": "2012-10-17", "Statement": [ { "Action": [ "iam:List*", "iam:PassRole" ], "Resource": [ "*" ], "Effect": "Allow", "Sid": "Stmt1565607714000" } ] }

蛇足

もっといい方法があるような気がしますが、わかったらアップデートします。