4
3

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.

お題は不問!Qiita Engineer Festa 2023で記事投稿!

【Python】JSONの特定のキーだけ残して不要部分は削除する

Posted at

はじめに

JSONの不要な要素を削除するコードを書いたので記事にしておきます

実装

import json

def filter_json(data):
    if isinstance(data, dict):
        filtered_data = {}
        for key, value in data.items():
            if key == "legacy":
                filtered_data[key] = value
            elif isinstance(value, (dict, list)):
                filtered_value = filter_json(value)
                if filtered_value:
                    filtered_data[key] = filtered_value
        return filtered_data
    elif isinstance(data, list):
        filtered_data = []
        for item in data:
            filtered_item = filter_json(item)
            if filtered_item:
                filtered_data.append(filtered_item)
        return filtered_data
    else:
        return None

# JSONファイルの読み込み
with open('input.json', 'r') as file:
    data = json.load(file)

# 不要なキーを削除
filtered_data = filter_json(data)

# 結果を新しいJSONファイルに書き込む
with open('output.json', 'w') as file:
    json.dump(filtered_data, file)

おわり

これからも使いそうです
コード資産できてよかったです

4
3
2

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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?