सूचियों के साथ कुछ ऐसा करने के लिए आपको JSONDecoder को उप-वर्गीकृत करने की आवश्यकता होगी। नीचे एक साधारण उदाहरण है जो object_pairs_hook
जैसा काम करता है। यह सी कार्यान्वयन के बजाय स्ट्रिंग स्कैनिंग के शुद्ध पायथन कार्यान्वयन का उपयोग करता है।
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])
स्रोत
2012-06-04 22:12:40