It follows my work:
import json
class TrivialSageJSON(json.JSONEncoder):
"""
http://docs.python.org/library/json.html#encoders-and-decoders
sage/devel/sage-main/sage/server/simple/twist.py (here there's a
"simple_jsonize")
"""
def default(self,o):
try:
if isinstance(o,sage.rings.real_mpfr.RealLiteral) or
isinstance(o,sage.rings.real_mpfr.RealNumber):
res = float(o)
elif isinstance(o,sage.rings.real_mpfr.Integer):
res = int(o)
else:
raise TypeError
except TypeError:
pass
else:
return res
return JSONEncoder.default(self, o)
if __name__ == "__main__":
print TrivialSageJSON().encode({"a": 1.8})
print TrivialSageJSON().encode({"a": sqrt(2).n()})
print TrivialSageJSON().encode({"a": 123})
If any thing better (more general) appears please let me know.
Thanks,
Pedro
On Feb 20, 12:17 am, Mike Hansen <[email protected]> wrote:
> On Fri, Feb 19, 2010 at 3:52 PM, jpc <[email protected]> wrote:
> > Should one do the "type cast" below for every int or float when using
> > sage ?
>
> > sage: type(float(x))
> > <type 'float'>
> > sage: json.dumps( {"a": float(x)} )
> > '{"a": 1.8}'
>
> > Any easier way ?
>
> You write a custom encoder to do this:
>
> http://docs.python.org/library/json.html#encoders-and-decoders
>
> --Mike
--
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/sage-support
URL: http://www.sagemath.org