in Python 2.7+ I can use the object_pairs_hook
in the builtin json module to change the type of the decoded objects. Is there anyway to do the same for lists?
One option is to go through the objects that I get as arguments to the hook and replace them with my own list type, but is there any other, smarter way?
To do something similar with lists you will need to subclass the JSONDecoder. Below is a simple example that work like object_pairs_hook
. This uses the pure python implementation of string scanning rather than the C implementation.
import json
class decoder(json.JSONDecoder):
def __init__(self, list_type=list, **kwargs):
json.JSONDecoder.__init__(self, **kwargs)
# Use the custom JSONArray
self.parse_array = self.JSONArray
# Use the python implemenation of the scanner
self.scan_once = json.scanner.py_make_scanner(self)
self.list_type=list_type
def JSONArray(self, s_and_end, scan_once, **kwargs):
values, end = json.decoder.JSONArray(s_and_end, scan_once, **kwargs)
return self.list_type(values), end
s = "[1, 2, 3, 4, 3, 2]"
print json.loads(s, cls=decoder) # [1, 2, 3, 4, 3, 2]
print json.loads(s, cls=decoder, list_type=list) # [1, 2, 3, 4, 3, 2]
print json.loads(s, cls=decoder, list_type=set) # set([1, 2, 3, 4])
print json.loads(s, cls=decoder, list_type=tuple) # set([1, 2, 3, 4, 3, 2])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With