Skip to content

ENH: Add JSON export option for DataFrame (take 2) #1263

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -685,6 +685,93 @@ def to_dict(self):
"""
return dict((k, v.to_dict()) for k, v in self.iteritems())

@classmethod
def from_json(cls, json, orient="columns", dtype=None, numpy=True):
"""
Convert JSON string to DataFrame

Parameters
----------
json : The JSON string to parse.
orient : {'split', 'records', 'index', 'columns', 'values'},
default 'columns'
The format of the JSON string
split : dict like
{index -> [index], columns -> [columns], data -> [values]}
records : list like [{column -> value}, ... , {column -> value}]
index : dict like {index -> {column -> value}}
columns : dict like {column -> {index -> value}}
values : just the values array
dtype : dtype of the resulting DataFrame
nupmpy: direct decoding to numpy arrays. default True but falls back
to standard decoding if a problem occurs.

Returns
-------
result : DataFrame
"""
from pandas._ujson import loads
df = None

if numpy:
try:
if orient == "columns":
args = loads(json, dtype=dtype, numpy=True, labelled=True)
if args:
args = (args[0].T, args[2], args[1])
df = DataFrame(*args)
elif orient == "split":
df = DataFrame(**loads(json, dtype=dtype, numpy=True))
elif orient == "values":
df = DataFrame(loads(json, dtype=dtype, numpy=True))
else:
df = DataFrame(*loads(json, dtype=dtype, numpy=True,
labelled=True))
except ValueError:
numpy = False
if not numpy:
if orient == "columns":
df = DataFrame(loads(json), dtype=dtype)
elif orient == "split":
df = DataFrame(dtype=dtype, **loads(json))
elif orient == "index":
df = DataFrame(loads(json), dtype=dtype).T
else:
df = DataFrame(loads(json), dtype=dtype)

return df

def to_json(self, orient="columns", double_precision=10,
force_ascii=True):
"""
Convert DataFrame to a JSON string.

Note NaN's and None will be converted to null and datetime objects
will be converted to UNIX timestamps.

Parameters
----------
orient : {'split', 'records', 'index', 'columns', 'values'},
default 'columns'
The format of the JSON string
split : dict like
{index -> [index], columns -> [columns], data -> [values]}
records : list like [{column -> value}, ... , {column -> value}]
index : dict like {index -> {column -> value}}
columns : dict like {column -> {index -> value}}
values : just the values array
double_precision : The number of decimal places to use when encoding
floating point values, default 10.
force_ascii : force encoded string to be ASCII, default True.

Returns
-------
result : JSON compatible string
"""
from pandas._ujson import dumps
return dumps(self, orient=orient, double_precision=double_precision,
ensure_ascii=force_ascii)

@classmethod
def from_records(cls, data, index=None, exclude=None, columns=None,
names=None, coerce_float=False):
Expand Down
71 changes: 71 additions & 0 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -919,6 +919,77 @@ def to_dict(self):
"""
return dict(self.iteritems())

@classmethod
def from_json(cls, json, orient="index", dtype=None, numpy=True):
"""
Convert JSON string to Series

Parameters
----------
json : The JSON string to parse.
orient : {'split', 'records', 'index'}, default 'index'
The format of the JSON string
split : dict like
{index -> [index], name -> name, data -> [values]}
records : list like [value, ... , value]
index : dict like {index -> value}
dtype : dtype of the resulting Series
nupmpy: direct decoding to numpy arrays. default True but falls back
to standard decoding if a problem occurs.

Returns
-------
result : Series
"""
from pandas._ujson import loads
s = None

if numpy:
try:
if orient == "split":
s = Series(**loads(json, dtype=dtype, numpy=True))
elif orient == "columns" or orient == "index":
s = Series(*loads(json, dtype=dtype, numpy=True,
labelled=True))
else:
s = Series(loads(json, dtype=dtype, numpy=True))
except ValueError:
numpy = False
if not numpy:
if orient == "split":
s = Series(dtype=dtype, **loads(json))
else:
s = Series(loads(json), dtype=dtype)

return s

def to_json(self, orient="index", double_precision=10, force_ascii=True):
"""
Convert Series to a JSON string

Note NaN's and None will be converted to null and datetime objects
will be converted to UNIX timestamps.

Parameters
----------
orient : {'split', 'records', 'index'}, default 'index'
The format of the JSON string
split : dict like
{index -> [index], name -> name, data -> [values]}
records : list like [value, ... , value]
index : dict like {index -> value}
double_precision : The number of decimal places to use when encoding
floating point values, default 10.
force_ascii : force encoded string to be ASCII, default True.

Returns
-------
result : JSON compatible string
"""
from pandas._ujson import dumps
return dumps(self, orient=orient, double_precision=double_precision,
ensure_ascii=force_ascii)

def to_sparse(self, kind='block', fill_value=None):
"""
Convert Series to SparseSeries
Expand Down
Loading