0
1

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 1 year has passed since last update.

Pythonでdict型(辞書型)のデータをインデント付きの見やすいJSONに変換してprintする

Last updated at Posted at 2023-10-08

Pythonの改修をしている時に「渡ってきてるdictの要素なんだろうな」と思ってとりあえずprintしたら複雑な階層構造のdictがダーッと1行で出力されて非常に困ってしまったので、見やすく表示する方法を備忘として残しておく。

環境

$ python --version
Python 3.12.0

やり方(実行例)

Pythonを対話モードで起動して以下を実行すれば良い。

import json

# JSONに変換して出力したいdictをここに定義
target_dict = {'food': {'fruits': {'red_fruits': ['apple', 'strawberry', 'cherry'], 'yellow_fruits': ['banana', 'pineapple', 'lemon'], 'green_fruits': ['kiwi', 'grape', 'green apple']}, 'vegetables': {'leafy_greens': ['spinach', 'lettuce', 'kale'], 'root_vegetables': ['potato', 'carrot', 'radish'], 'nightshades': ['tomato', 'cucumber', 'bell pepper']}}, 'animals': {'mammals': {'carnivores': ['lion', 'tiger', 'bear'], 'rodents': ['squirrel', 'guinea pig', 'beaver'], 'ungulates': ['horse', 'cow', 'deer']}, 'birds': {'birds_of_prey': ['eagle', 'hawk', 'vulture'], 'waterfowl': ['duck', 'pelican', 'seagull'], 'songbirds': ['nightingale', 'mockingbird', 'canary']}, 'reptiles': {'snakes': ['anaconda', 'boa constrictor', 'cobra'], 'turtles': ['red-eared slider', 'box turtle', 'sea turtle'], 'lizards': ['iguana', 'gecko', 'chameleon']}}, 'space': {'constellations': {'northern_hemisphere': ['Ursa Major', 'Cassiopeia', 'Perseus'], 'southern_hemisphere': ['Centaurus', 'Phoenix', 'Southern Cross']}, 'planets': {'inner_planets': ['Mercury', 'Venus', 'Earth', 'Mars'], 'gas_giants': ['Jupiter', 'Saturn'], 'ice_giants': ['Uranus', 'Neptune'], 'dwarf_planets': ['Pluto', 'Eris']}, 'astronauts': {'NASA': ['Neil Armstrong', 'Buzz Aldrin', 'Sally Ride'], 'Roscosmos': ['Yuri Gagarin', 'Valentina Tereshkova'], 'ESA': ['Thomas Pesquet', 'Samantha Cristoforetti']}}}

# インデント4のJSONデータに変換
json_data = json.dumps(target_dict, indent=4)
print(json_data)

実行結果

階層構造がわからなかった1行の複雑なdictデータが非常にわかりやすく出力される。

{
    "food": {
        "fruits": {
            "red_fruits": [
                "apple",
                "strawberry",
                "cherry"
            ],
            "yellow_fruits": [
                "banana",
                "pineapple",
                "lemon"
            ],
            "green_fruits": [
                "kiwi",
                "grape",
                "green apple"
            ]
        },
        "vegetables": {
            "leafy_greens": [
                "spinach",
                "lettuce",
                "kale"
            ],
            "root_vegetables": [
                "potato",
                "carrot",
                "radish"
            ],
            "nightshades": [
                "tomato",
                "cucumber",
                "bell pepper"
            ]
        }
    },
    "animals": {
        "mammals": {
            "carnivores": [
                "lion",
                "tiger",
                "bear"
            ],
            "rodents": [
                "squirrel",
                "guinea pig",
                "beaver"
            ],
            "ungulates": [
                "horse",
                "cow",
                "deer"
            ]
        },
        "birds": {
            "birds_of_prey": [
                "eagle",
                "hawk",
                "vulture"
            ],
            "waterfowl": [
                "duck",
                "pelican",
                "seagull"
            ],
            "songbirds": [
                "nightingale",
                "mockingbird",
                "canary"
            ]
        },
        "reptiles": {
            "snakes": [
                "anaconda",
                "boa constrictor",
                "cobra"
            ],
            "turtles": [
                "red-eared slider",
                "box turtle",
                "sea turtle"
            ],
            "lizards": [
                "iguana",
                "gecko",
                "chameleon"
            ]
        }
    },
    "space": {
        "constellations": {
            "northern_hemisphere": [
                "Ursa Major",
                "Cassiopeia",
                "Perseus"
            ],
            "southern_hemisphere": [
                "Centaurus",
                "Phoenix",
                "Southern Cross"
            ]
        },
        "planets": {
            "inner_planets": [
                "Mercury",
                "Venus",
                "Earth",
                "Mars"
            ],
            "gas_giants": [
                "Jupiter",
                "Saturn"
            ],
            "ice_giants": [
                "Uranus",
                "Neptune"
            ],
            "dwarf_planets": [
                "Pluto",
                "Eris"
            ]
        },
        "astronauts": {
            "NASA": [
                "Neil Armstrong",
                "Buzz Aldrin",
                "Sally Ride"
            ],
            "Roscosmos": [
                "Yuri Gagarin",
                "Valentina Tereshkova"
            ],
            "ESA": [
                "Thomas Pesquet",
                "Samantha Cristoforetti"
            ]
        }
    }
}

似ているメソッドとしてjson.dump()があるが、そちらはファイルとして保存する際に使用するもので、今回の辞書型を文字列に変換するjson.dumps()とは異なるので注意。

余談

dictの出力形式を整えて表示するならpprintモジュールが良いらしいが、今一つ使い方がわからなかった。

jsonモジュールなら引数でインデント指定ができて簡単に見慣れたJSONデータに出力できるため今回使用モジュールとして選んだ次第。

余裕がある時にpprintの使い方を調べて比較、追記します。

参考

json — JSON encoder and decoder - Python 3.12.0 documentation

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?