LoginSignup
12
6

More than 1 year has passed since last update.

Pythonでjsonlを読み書きする

Posted at

jsonlとは

改行区切りの1レコードがjsonになっているデータのことです。
こんなデータ↓

{"name": "Gilbert", "wins": [["straight", "7♣"], ["one pair", "10♥"]]}
{"name": "Alexa", "wins": [["two pair", "4♠"], ["two pair", "9♠"]]}
{"name": "May", "wins": []}
{"name": "Deloise", "wins": [["three of a kind", "5♣"]]}

pandas使わない方法

ファイル読み込み

import json
with open('hoge.jsonl') as f:
    jsonl_data = [json.loads(l) for l in f.readlines()]

ファイル出力

with open('fuga.jsonl', 'w') as f:
    f.writelines([json.dumps(l) for l in jsonl_data])

pandas使う方法

ファイル読み込み

import pandas as pd
df = pd.read_json('piyo.jsonl', orient='records', lines=True)

ファイル出力

df.to_json('piyopiyo.jsonl', orient='records', force_ascii=False, lines=True)

感想

  • 備忘録です。
  • pandasで読んだり、readlines()で読んだりしてるなぁと思ったので書いておきました。
12
6
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
12
6