16
2

More than 1 year has passed since last update.

Pythonでndjsonファイルを扱う方法

Posted at

はじめに

最近ndjson形式のファイルを扱うことが増えてきたため、今回はPythonでndjson形式のファイルを扱う方法を簡潔にまとめてみた。
ndjsonというモジュールがあるらしいので、それを使用してみる。

参考記事など

テスト用ndjsonファイル準備

以下のような値をもつファイルを作成し、test_input.ndjsonとして保存した。

{"username":"Mac","hobby":["baseball","soccer","tennis"]}
{"username":"John","hobby":["baseball","cooking"]}
{"username":"Miki","hobby":["cooking","reading"]}
{"username":"Andy","hobby":["baseball","soccer"]}

モジュールのインストール

以下のコマンドでndjsonモジュールがインストールできる。

pip install ndjson

ndjsonモジュールの使用方法

ndjsonファイルの読み込み

ndjsonファイルの読み込みは以下のように書くことができる。

import ndjson

with open('test_input.ndjson', encoding='UTF-8') as f:
    input_data = ndjson.load(f)
    print(input_data)
    print(type(input_data))

読み込み結果は以下のようになる。このように ndjson.load() を使用するとjsonをリスト形式で取得できる。

[
 {'username': 'Mac', 'hobby': ['baseball', 'soccer', 'tennis']}, 
 {'username': 'John', 'hobby': ['baseball', 'cooking']}, 
 {'username': 'Miki', 'hobby': ['cooking', 'reading']}, 
 {'username': 'Andy', 'hobby': ['baseball', 'soccer']}
]
<class 'list'>

また、 ndjson.dumps() を使用するとテキストへ変換することができる。

import ndjson

with open('test_input.ndjson', encoding='UTF-8') as f:
    input_data = ndjson.load(f)
    text_data = ndjson.dumps(input_data)
    print(text_data)
    print(type(text_data))

結果は以下のようになる。どうやらテキストは改行されて表示される(改行コードが入っている)らしい。

{"username": "Mac", "hobby": ["baseball", "soccer", "tennis"]}
{"username": "John", "hobby": ["baseball", "cooking"]}
{"username": "Miki", "hobby": ["cooking", "reading"]}
{"username": "Andy", "hobby": ["baseball", "soccer"]}
<class 'str'>

ndjsonファイルへの書き込み

ndjsonファイルへの書き込みは、以下のように ndjson.dumps() を使用する。
なお、 ndjson.dump() を使用する際は、引数にリスト型オブジェクトを入れる必要があるので、テキストなどは ndjson.loads() で型を変更する必要がある。

import ndjson

with open('test_input.ndjson', encoding='UTF-8') as f:
    input_data = ndjson.load(f)
    text_data = ndjson.dumps(input_data)
    converted_data = ndjson.loads(text_data)

with open('test_json_output.ndjson', 'w', encoding='UTF-8') as f:
    ndjson.dump(converted_data, f)

ちなみに、テキストをハードコードする場合は、以下のように改行コードを入れてあげればよい。

import ndjson

text = '{"username": "Mac", "hobby": ["baseball", "soccer", "tennis"]}\n{"username": "John", "hobby": ["baseball", "cooking"]}'
    converted_data = ndjson.loads(text)
    
with open('test_json_output.ndjson', 'w', encoding='UTF-8') as f:
    ndjson.dump(converted_data, f)

まとめ

今回は、Pythonでndjson簡単に扱うことができるようになるndjsonモジュールについて簡潔にまとめてみた。jsonモジュールと同じような感じで簡単に利用できるので、ぜひ試してみてほしい。

16
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
16
2