5

Possible Duplicate:
Python JSON serialize a Decimal object

Task: to convert a dict containing a mix of data-types (integer/strint/decimal/...) as values, into JSON array.

I know how to convert a python dict into JSON:

D = {key1:val1, key2,val2}
import json
jD = json.dumps(D)

I also know that decimal value has to be converted into a string, otherwise python will throw error that 'decimal is not json serializable'.

So I would need to iterate through the dict to look for the data-type.

for key in D.keys():
    if type(key) == '<class "decimal.Decimal">': ## this is erroneous. pl. suggest correction
    D[key] = str(D[key])

But this programming is involving hand-coding and hard-coding.

If I get a nested dictionary structure, again hard-coding would be required (which is wrong).

Is there any other method/trick to get JSON array from whatever data-type in dict?

Community
  • 1
  • 1
Vineet
  • 624
  • 1
  • 11
  • 26

2 Answers2

4

Note that JSON cannot express decimals, only floats and strings. Therefore, you should convert your decimals to strings, like this:

keys_for_json = {str(k):v for k,v in keys.items()}
phihag
  • 278,196
  • 72
  • 453
  • 469
3

Why not subclass the JSONEncoder? It's simple and clean:

class DecimalEncoder(json.JSONEncoder):
    def _iterencode(self, o, markers=None):

        if isinstance(o, decimal.Decimal):  # isinstance() is better than type(), because it handles inheritance
            return (str(o) for o in [o])

        return super(DecimalEncoder, self)._iterencode(o, markers)
Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
  • I am looking for a method which would not require any manipulation by hand. @JMax has suggested simplejson.dumps with as_decimal=True. that works but gives json object enclosed into square brackets []. Any idea to avoid that? Thanks. – Vineet Feb 14 '12 at 13:08
  • @Vineet: your question as you've written here has been closed. If you still have any issue (still enclosed into brackets?), please feel free to ask a new one giving all the necessary information. – JMax Feb 14 '12 at 13:38