Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read json file as pandas dataframe?

Tags:

I am using python 3.6 and trying to download json file (350 MB) as pandas dataframe using the code below. However, I get the following error:

data_json_str = "[" + ",".join(data) + "] "TypeError: sequence item 0: expected str instance, bytes found 

How can I fix the error?

import pandas as pd  # read the entire file into a python array with open('C:/Users/Alberto/nutrients.json', 'rb') as f:    data = f.readlines()  # remove the trailing "\n" from each line data = map(lambda x: x.rstrip(), data)  # each element of 'data' is an individual JSON object. # i want to convert it into an *array* of JSON objects # which, in and of itself, is one large JSON object # basically... add square brackets to the beginning # and end, and have all the individual business JSON objects # separated by a comma data_json_str = "[" + ",".join(data) + "]"  # now, load it into pandas data_df = pd.read_json(data_json_str) 
like image 426
Alberto Alvarez Avatar asked Feb 04 '18 23:02

Alberto Alvarez


People also ask

How do I read a JSON file into a Pandas DataFrame?

Reading JSON Files using Pandas To read the files, we use read_json() function and through it, we pass the path to the JSON file we want to read. Once we do that, it returns a “DataFrame”( A table of rows and columns) that stores data.

Can Pandas import JSON?

Pandas allow you to convert a list of lists into a Dataframe and specify the column names separately. A JSON parser transforms a JSON text into another representation must accept all texts that conform to the JSON grammar. It may accept non-JSON forms or extensions.


2 Answers

From your code, it looks like you're loading a JSON file which has JSON data on each separate line. read_json supports a lines argument for data like this:

data_df = pd.read_json('C:/Users/Alberto/nutrients.json', lines=True) 

Note
Remove lines=True if you have a single JSON object instead of individual JSON objects on each line.

like image 102
cs95 Avatar answered Sep 27 '22 23:09

cs95


Using the json module you can parse the json into a python object, then create a dataframe from that:

import json import pandas as pd with open('C:/Users/Alberto/nutrients.json', 'r') as f:     data = json.load(f) df = pd.DataFrame(data) 
like image 24
James Doepp - pihentagyu Avatar answered Sep 27 '22 23:09

James Doepp - pihentagyu