LoginSignup
6
3

More than 3 years have passed since last update.

整形済みJSON文字列を1行JSONに変換(圧縮)する

Last updated at Posted at 2020-02-19

JSON文字列を1行JSONに変換(圧縮)する際に方法を確認したのでメモ。

方法

以下の2通りの方法を紹介する。

  • Python
  • jqコマンド

ファイルに記載された以下のようなJSON文字列を前提にする。

file.py
{
    "Records": [
        {
            "database": {
                "NewImage": {
                    "eventId": {
                        "S": "a4207f7a-5f04-471b-a338-1175182eaa6d"
                    },
                    "isCompleted": {
                        "BOOL": True
                    }
                },
                "OldImage": {
                    "eventId": {
                        "S": "a4207f7a-5f04-471b-a338-1175182eaa6d"
                    },
                    "isCompleted": {
                        "BOOL": False
                    }
                }
            }
        }
    ]
}

方法その1:Pythonを利用

$ python
>>> import json
>>> f = open("file.json")
>>> json.dumps(f.read()).replace("\\n","").replace("\\","").replace("    ", "")
'"{"Records": [{"database": {"NewImage": {"eventId": {"S": "a4207f7a-5f04-471b-a338-1175182eaa6d"},"isCompleted": {"BOOL": True}},"OldImage": {"eventId": {"S": "a4207f7a-5f04-471b-a338-1175182eaa6d"},"isCompleted": {"BOOL": False}}}}]}"'

.replace(" ", "")ではインデント(スペース4つ)を置換して削除している。JSON文字列中で異なる文字列をインデントとしている場合は本部分の置換元を変更すれば良い。

方法その2:jqコマンドを利用

基本的にはcat <ファイル名> | jq -cで対処可能である。

しかし、jqはTrueFalseをbooleanとして扱えないため、今回のfile.jsonに対してそのまま実行しようとすると下記のようなエラーとなる。

$ cat file.json | jq -c
parse error: Invalid numeric literal at line 11, column 0

よって、Truetrueへ、Falsefalseへ事前に変更する必要がある。事前にfile.jsonを手直しした場合は以下のように実行可能である。

$ cat file.json | jq -c
{"Records":[{"database":{"NewImage":{"eventId":{"S":"a4207f7a-5f04-471b-a338-1175182eaa6d"},"isCompleted":{"BOOL":true}},"OldImage":{"eventId":{"S":"a4207f7a-5f04-471b-a338-1175182eaa6d"},"isCompleted":{"BOOL":false}}}}]}

以上

6
3
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
6
3