Skip to content

Instantly share code, notes, and snippets.

@mntone
Created February 25, 2025 07:30
Show Gist options
  • Save mntone/11c2738b040a7edb087daf50d3d92224 to your computer and use it in GitHub Desktop.
Save mntone/11c2738b040a7edb087daf50d3d92224 to your computer and use it in GitHub Desktop.
このスクリプトは、指定されたJSONファイルからCLIで指定したJSONPathに一致するデータを削除し、結果を新しいファイルに保存します。出力ファイル名はオプションで指定でき、未指定の場合は元のファイル名に日時のサフィックスを追加して保存されます。

JSONPathによるデータ削除スクリプト

概要

このスクリプトは、指定されたJSONファイルから特定のJSONPathに一致するデータを削除し、新しいJSONファイルとして出力します。

使い方

基本的なコマンド

python script.py data.json '$.store.book[*].price'

上記のコマンドでは、data.json$.store.book[*].price に一致するすべてのデータを削除します。

複数のJSONPathを指定

python script.py data.json '$.store.book[*].price' '$.store.bicycle.color

複数のJSONPathを指定すると、それらに一致するデータがすべて削除されます。

出力ファイル名の指定

python script.py data.json '$.store.book[*].price' --output result.json

オプション --output を指定すると、結果を result.json に保存します。

出力ファイル名のデフォルト動作

--output を指定しない場合、元のファイル名に現在の日時が追加されます。 例えば、data.json の場合、以下のようなファイル名になります:

data_20250225_153000.json

スクリプトの詳細

  • jsonpath-ng を使用してJSONPathを解析
  • 指定したJSONPathに一致する要素をリストや辞書から削除
  • 削除後のJSONデータを新しいファイルとして保存

必要なライブラリ

事前に jsonpath-ng をインストールする必要があります。

pip install jsonpath-ng

注意点

  • 削除対象のデータが見つからない場合、JSONは変更されません。
  • リスト内の要素を削除する際は、その要素の順番によって削除後のリストの構造が変わる可能性があります。

まとめ

このスクリプトを使うことで、JSONファイルから特定のデータを簡単に削除し、編集後のデータを新しいファイルに保存できます。

# Copyright (C) 2025 mntone. All rights reserved.
# This file is released under MIT License.
import json
import argparse
import datetime
from jsonpath_ng import parse
def remove_json_paths(json_data, paths):
for path in paths:
jsonpath_expr = parse(path)
matches = jsonpath_expr.find(json_data)
for match in matches:
parent = match.context.value
if isinstance(parent, list):
parent.remove(match.value)
elif isinstance(parent, dict):
del parent[match.path.fields[0]]
return json_data
def main():
parser = argparse.ArgumentParser(description='Remove JSON data by JSONPath')
parser.add_argument('json_file', type=str, help='Path to JSON file')
parser.add_argument('json_paths', type=str, nargs='+', help='JSONPath expressions to remove')
parser.add_argument('--output', type=str, help='Output file name (optional)')
args = parser.parse_args()
with open(args.json_file, 'r', encoding='utf-8') as f:
json_data = json.load(f)
updated_json = remove_json_paths(json_data, args.json_paths)
output_file = args.output if args.output else f"{args.json_file.rsplit('.', 1)[0]}_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(updated_json, f, indent=2, ensure_ascii=False)
print(f"Updated JSON saved to {output_file}.")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment