4

I have, an an input, integers. I build a dict out of them (as values). I then dump it to JSON, to be reused elsewhere.

I ultimately (at the "elsewhere") need to use these integers as strings. I can therefore do the conversion

  • upstream (when building the dict)
  • or on the receiving side (the "elsewhere").

There will be, no matter the solution, plenty of str() all over the code. I am looking for a cleaner way to convert all the int into str in that specific case.

One idea is to recursively parse the dict once it is built, just before the json.dumps(), and make the conversion there. I am wondering, though, if there is not a way to handle this while dumping the JSON? Possibly with json.JSONEncoder? (which to be frank I do not understand much)

Community
  • 1
  • 1
WoJ
  • 27,165
  • 48
  • 180
  • 345

1 Answers1

6

Assuming that on the receiving end you are running Python, you could convert the ints to strings upon loading the JSON by using the parse_int parameter:

import json

test = {'foo':1, 'bar':[2,3]}
json_str = json.dumps(test)
print(json.loads(json_str, parse_int=str))

yields

{u'foo': '1', u'bar': ['2', '3']}

Per the docs:

parse_int, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float).

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • Perfect, thank you - this is exactly what I was looking for. I was suspecting that `json` could be capable to do the conversion, what drove me off is (in the docs you quote) "By default this is equivalent to int(num_str).". I read it as being the opposite of what I want to do, now after reading with understanding (and with the help of your code) it is clear. – WoJ Jan 25 '15 at 16:26