改行で区切られたJSONファイルの種類を文字列から整数に変換し、nullを処理します。

改行で区切られたJSONファイルの種類を文字列から整数に変換し、nullを処理します。

次のように改行で区切られたJSONがあります。

{"leagueId": "1", "name": "the ballers"}
{"team": "2", "leagueId": "1", "name": "the hoopers"}
{"team": "3", "leagueId": "1", "name": "the gamerrs"}
{"team": "4", "leagueId": "1", "name": "the drivers"}
{"team": "5", "leagueId": "1", "name": "the jumpers"}
{"team": "6", "leagueId": "1", "name": "the riserss"}

チーム、リーグIDどちらも整数でなければならず、このNDJSONを変更してこれらの文字列を整数に変換したいと思います。私たちが望む結果は次のとおりです。

{"leagueId": 1, "name": "the ballers"}
{"team": 2, "leagueId": 1, "name": "the hoopers"}
{"team": 3, "leagueId": 1, "name": "the gamerrs"}
{"team": 4, "leagueId": 1, "name": "the drivers"}
{"team": 5, "leagueId": 1, "name": "the jumpers"}
{"team": 6, "leagueId": 1, "name": "the riserss"}

文字列から整数[チーム、リーグID]に変換する必要がある列のリスト/配列を知っていると仮定すると、この変換はどのように実行されますか? (a)thisのようなツールを使用するbashコマンドを介して可能ですかjq、または(b)Pythonソリューションはありますか? NDJSON全体のサイズは約10 GBであり、これは毎日のデータ収集パイプラインの1つのステップであるため、パフォーマンスが非常に重要です。

編集する: jq -c '{leagueId: .leagueId | tonumber, team: .team | tonumber, name: .name}' tmp/testNDJSON.json > tmp/new_output.json次のようにこれは最初のJSONで欠落していない場合は機能しますteam。助けてくれてありがとう!

ベストアンサー1

jq  -c '.leagueId |= tonumber | (.team // empty) |= tonumber' file

これはleagueIdその中の各オブジェクトを数値に変換し、存在し、teamnullでない場合は値を変換します。

キーセットがある場合は数値に変換するように一般化されました。

jq -c --argjson keys '["team", "leagueId"]' \
    '($keys[] as $key | .[$key] // empty) |= tonumber' file

使用jo次のリストを作成します。

jq -c --argjson keys "$(jo -a team leagueId)"  \
    '($keys[] as $key | .[$key] // empty) |= tonumber' file

ここで何が起こるのかは、null以外の値を持つ既存のキーを持つオブジェクトから値を生成するために一連の文字列に.[$key] // emptyステートメントが使用されることです。その後、この値は数値に変換されます。文字列は、コマンドラインから渡された配列から取得されます。$key$key$key

おすすめ記事