2

Hi I have made a custom JSONEncoder and happened to run into this issue. When I use the dumps function of simplejson the nested object gets serialize as a string. For example I use this:

simplejson.dumps({'lat': obj.lat, 'lon': obj.lon})

And get this:

{
website: "http://something.org",
location: "{"lat": 12.140158037163658, "lon": -86.24754807669069}"
}

If you see location object is with double quotes is there a way I can specify location object to be dump properly as a JSON object (without the double quotes).

Edit

class jsonEncoder(simplejson.JSONEncoder):
    def default(self, obj):
        isinstance(obj, db.GeoPt):
            return simplejson.dumps({'lat': obj.lat, 'lon': obj.lon})

        else:
            return simplejson.JSONEncoder.default(self, obj)
3
  • The quotes are not optional in JSON (unlike JavaScript object literals). You have to add quotes for your example to be proper JSON. Commented Sep 2, 2012 at 2:16
  • Looks like that the problem resides in your JSONEncoder implementation. You may want to add your implementation here to get better help. Commented Sep 2, 2012 at 3:31
  • @Necronet : alternatively you could pass dict with lat, lon argument to JsonEncoder . Commented Oct 13, 2014 at 7:47

1 Answer 1

4

Don't return a string from default() when obj is a db.GeoPt. Instead, return the dict with keys 'lat' and 'lon', and let the JSON library serialize the dict.

Try this:

class jsonEncoder(simplejson.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, db.GeoPt):
            return {'lat': obj.lat, 'lon': obj.lon}
        else:
            return simplejson.JSONEncoder.default(self, obj)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.