Stefan D
Stefan D

Reputation: 1259

Is there a Python JSON encoder which JUST works?

I understand this may be a stupid question in many contexts, but does there exist a Python JSON encoder which converts everything it does not understand (eg. float32, float64, high precision decimal, etc.) to string?

I am having a hard time iterating multiple levels deep through my data structures to convert all datatypes json, simplejson & ujson modules complain about.

Upvotes: 0

Views: 112

Answers (2)

larsks
larsks

Reputation: 311606

It's pretty easy to make the standard json module do what you want by setting the default parameter to a function that just calls str() on its argument:

import json

class MyObject(object):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return str(self.value)

print json.dumps(
    {
        'simple_string': 'i encode easily',
        'simple_int': 42,
        'complex': MyObject('this is a test')
    }, default=str, indent=2)

This will call string(obj) for any obj that is not one of the types the json module is able to encode natively. The above example results in:

{
  "simple_int": 42, 
  "simple_string": "i encode easily", 
  "complex": "this is a test"
}

Upvotes: 4

Marcin
Marcin

Reputation: 49826

You could try JSONPickle (I am a contributor)

Upvotes: -1

Related Questions