Open In App

How to Fix: ValueError: Trailing data?

In this article, we will discuss how we may fix ValueError: Trailing data in Python.

This problem commonly occurs when you attempt to import a JSON file into a pandas DataFrame, although the data is written in lines separated by endlines like ‘\n‘. 



Like in this sample json file:



JSON Used:

Error:

Let’s examine what happens if we try to import this json file into pandas.




# This code fix ValueError: Trailing data
import pandas as pd
  
df = pd.read_json('sample_json.json')
print(df.head())

Output:

ValueError: Trailing data

Because the “ABOUT” item in our JSON file contains ‘\n’ to indicate endlines, we get an error.

How to Fix:

For this, we will use lines = True Read the file as a json object per line.




# This code fix ValueError: Trailing data
import pandas as pd
  
df = pd.read_json('sample_json.json', lines = True)
print(df.head())

Output:

   ID NAME
0   1  abc
1   2  def
2   3  ghi
3   4  jkl

Notice that we’re able to properly import the JSON file into a pandas DataFrame without any issues. This was fixed by changing the lines attribute of pandas read json method into True. The line attribute reads the file as a json object per line.

Article Tags :