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 <mhan...@gmail.com> wrote:
> On Fri, Feb 19, 2010 at 3:52 PM, jpc <pedrocruzave...@gmail.com> 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 sage-support@googlegroups.com
To unsubscribe from this group, send email to 
sage-support+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/sage-support
URL: http://www.sagemath.org

Reply via email to