4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

jsonファイルを環境変数に展開する

Posted at

概要

jsonファイルに記載した内容を環境変数にも展開したい場合があったので調べた内容をメモする

ファイル構成

ファイル構成
├ config.json
└ json.sh

JSONファイル作成

下記の内容で作ってみる。

config.json
{
  "hoge": "hello_world",
  "fuga": "example_value"
}

シェルを作成する

下記の内容で作ってみました。

json.sh
# !/bin/bash

JSON=`cat config.json`

KEYS=$(echo $JSON | jq -r 'keys[] as $k | "\($k)=\(.[$k])"')
i=0
for e in ${KEYS[@]}; do
    # キーと値を分割する
    arr=(`echo "${e}" | tr -s '=' ' '`)
    # キーを大文字に変換して変数定義する 
    export ${arr[0]^^}="${arr[1]}"
    let i++
done

echo "HOGE: ${HOGE}"
echo "FUGA: ${FUGA}"

テスト

実行してみる

ターミナル
$ ./json.sh
HOGE: hello
FUGA: example

このままだと

ターミナル
$ echo ${HOGE}

$ echo ${FUGA}

となり、シェルの中だけ有効となる。

環境変数として定義する

sourceコマンドを使う。

ターミナル
$ source json.sh
HOGE: hello_world
FUGA: example_value

動作確認してみる。

ターミナル
$ echo $HOGE
hello_world

$ echo $FUGA
example_value

まとめ

jsonファイルに定義する値に半角スペースがあるとそこで切れてしまうなどの問題もあり、
あまりいいやり方ではない感じです。

jqコマンドについては、もう少し勉強が必要そうです。

以上

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?