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)
Answer from coldspeed95 on Stack OverflowNote
Removelines=Trueif you have a single JSON object instead of individual JSON objects on each line.
Videos
How to read a JSON column in Pandas?
import pandas as pd df = pd.DataFrame({'col': ['{"name": "John", "age": 30}', '{"name": "Jane", "age": 25}']}) df['col'] = df['col'].apply(pd.json_normalize)
This will convert the JSON strings in the column into structured data.
How to load JSON string into Pandas DataFrame?
import pandas as pd import json json_string = '{"name": "John", "age": 30}' df = pd.read_json(json.loads(json_string))
How to load JSON file with Pandas?
import pandas as pd df = pd.read_json('file.json')
This reads the JSON file into a Pandas DataFrame.
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
Removelines=Trueif you have a single JSON object instead of individual JSON objects on each line.
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)
I found a quick and easy solution to what I wanted using json_normalize() included in pandas 1.01.
from urllib2 import Request, urlopen
import json
import pandas as pd
path1 = '42.974049,-81.205203|42.974298,-81.195755'
request=Request('http://maps.googleapis.com/maps/api/elevation/json?locations='+path1+'&sensor=false')
response = urlopen(request)
elevations = response.read()
data = json.loads(elevations)
df = pd.json_normalize(data['results'])
This gives a nice flattened dataframe with the json data that I got from the Google Maps API.
Check this snip out.
# reading the JSON data using json.load()
file = 'data.json'
with open(file) as train_file:
dict_train = json.load(train_file)
# converting json dataset from dictionary to dataframe
train = pd.DataFrame.from_dict(dict_train, orient='index')
train.reset_index(level=0, inplace=True)
Hope it helps :)