core
prairielearn.core ¶
Utilities for building questions and elements in PrairieLearn.
from prairielearn import ...
# or ...
from prairielearn.core import ...
from_json ¶
Converts a JSON serialized value (from to_json
) back to its original type.
If v has the format {'_type': ..., '_value': ...}
as would have been created
using to_json(...)
, then it is replaced according to the following table:
JSON _type field |
Python type |
---|---|
complex |
complex |
np_scalar |
numpy scalar defined by _concrete_type |
ndarray |
non-complex ndarray |
complex_ndarray |
complex ndarray |
sympy |
sympy.Expr |
sympy_matrix |
sympy.Matrix |
dataframe |
pandas.DataFrame |
dataframe_v2 |
pandas.DataFrame |
networkx_graph |
corresponding networkx graph |
missing | input value v returned |
If v encodes an ndarray and has the field '_dtype'
, this function recovers
its dtype.
If v does not have the format {'_type': ..., '_value': ...}
, then it is
returned without change.
to_json ¶
to_json(
v: Any | _JSONPythonType,
*,
df_encoding_version: Literal[1, 2] = 1,
np_encoding_version: Literal[1, 2] = 1,
) -> Any | _JSONSerializedType
Convert a value to a JSON serializable format.
If v has a standard type that cannot be json serialized, it is replaced with
a {'_type': ..., '_value': ...}
pair that can be json serialized.
This is a complete table of the mappings:
Type | JSON _type field |
notes |
---|---|---|
complex scalar | complex |
including numpy |
non-complex ndarray | ndarray |
assumes each element can be json serialized |
complex ndarray | complex_ndarray |
|
sympy.Expr |
sympy |
any scalar sympy expression |
sympy.Matrix |
sympy_matrix |
|
pandas.DataFrame |
dataframe |
df_encoding_version=1 |
pandas.DataFrame |
dataframe_v2 |
df_encoding_version=2 |
networkx graph type | networkx_graph |
|
numpy scalar | np_scalar |
np_encoding_version=2 |
any | v |
if v can be json serialized |
Note
The 'dataframe_v2'
encoding allows for missing and date time values whereas
the 'dataframe'
(default) does not. However, the 'dataframe'
encoding allows for complex
numbers while 'dataframe_v2'
does not.
If np_encoding_version
is set to 2, then numpy scalars serialize using '_type': 'np_scalar'
.
If df_encoding_version
is set to 2, then pandas DataFrames serialize using '_type': 'dataframe_v2'
.
See from_json for details about the differences between encodings.
If v is an ndarray, this function preserves its dtype (by adding '_dtype'
as
a third field in the dictionary).
If v can be json serialized or does not have a standard type, then it is returned without change.