Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open .ndjson file in Python?

I have .ndjson file that has 20GB that I want to open with Python. File is to big so I found a way to split it into 50 peaces with one online tool. This is the tool: https://pinetools.com/split-files

Now I get one file, that has extension .ndjson.000 (and I do not know what is that)

I'm trying to open it as json or as a csv file, to read it in pandas but it does not work. Do you have any idea how to solve this?

import json
import pandas as pd

First approach:

df = pd.read_json('dump.ndjson.000', lines=True)

Error: ValueError: Unmatched ''"' when when decoding 'string'

Second approach:

with open('dump.ndjson.000', 'r') as f:

     my_data = f.read() 

print(my_data)

Error: json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 104925061 (char 104925060)

I think the problem is that I have some emojis in my file, so I do not know how to encode them?

like image 778
taga Avatar asked Apr 14 '26 23:04

taga


2 Answers

ndjson is now supported out of the box with argument lines=True

import pandas as pd

df = pd.read_json('/path/to/records.ndjson', lines=True)
df.to_json('/path/to/export.ndjson', lines=True)
like image 152
Banane Avatar answered Apr 17 '26 13:04

Banane


I think the pandas.read_json cannot handle ndjson correctly.

According to this issue you can do sth. like this to read it.

import ujson as json
import pandas as pd

records = map(json.loads, open('/path/to/records.ndjson'))
df = pd.DataFrame.from_records(records)

P.S: All credits for this code go to KristianHolsheimer from the Github Issue

like image 22
Shogoki Avatar answered Apr 17 '26 12:04

Shogoki