Python: Change list type for json decoding -


in python 2.7+ can use object_pairs_hook in builtin json module change type of decoded objects. there anyway same lists?

one option go through objects arguments hook , replace them own list type, there other, smarter way?

to similar lists need subclass jsondecoder. below simple example work object_pairs_hook. uses pure python implementation of string scanning rather c implementation.

import json  class decoder(json.jsondecoder):      def __init__(self, list_type=list,  **kwargs):         json.jsondecoder.__init__(self, **kwargs)         # use custom jsonarray         self.parse_array = self.jsonarray         # use python implemenation of 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]) 

Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -