Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Change list type for json decoding

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?

like image 953
user408952 Avatar asked Jun 04 '12 17:06

user408952


1 Answers

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])
like image 90
Jesse Harris Avatar answered Oct 06 '22 23:10

Jesse Harris