Python json.encoder.JSONEncoder() Examples

The following are 7 code examples of json.encoder.JSONEncoder(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module json.encoder , or try the search function .
Example #1
Source File: json.py    From yosai with Apache License 2.0 6 votes vote down vote up
def __init__(self, encoder_options: Dict[str, Any] = None,
                 decoder_options: Dict[str, Any] = None, encoding: str = 'utf-8',
                 custom_type_key: str = '__type__'):
        self.encoding = encoding
        self.custom_type_key = custom_type_key
        self._marshallers = OrderedDict()  # class -> (typename, marshaller function)
        self._unmarshallers = OrderedDict()  # typename -> (class, unmarshaller function)

        self.encoder_options = encoder_options or {}

        self.encoder_options['default'] = resolve_reference(self.encoder_options.get('default'))
        self._encoder = JSONEncoder(**self.encoder_options)

        self.decoder_options = decoder_options or {}
        self.decoder_options['object_hook'] = resolve_reference(
            self.decoder_options.get('object_hook'))
        self.decoder_options['object_pairs_hook'] = resolve_reference(
            self.decoder_options.get('object_pairs_hook'))
        self._decoder = JSONDecoder(**self.decoder_options) 
Example #2
Source File: qqapi.py    From PyLinuxQQ with GNU General Public License v2.0 6 votes vote down vote up
def send_msg(self,to_uin,msg=u'hello world'):
        '''
        url = 'http://d.web2.qq.com/channel/send_buddy_msg2'
        data_poll = {
            'r': '{"to":'+str(to_uin)+',"content":"[\"'+msg+u'\",[\"font\",{\"name\":\"宋体\",\"size\":10,\"style\":[0,0,0],\"color\":\"000000\"}]]","face":147,"clientid":'+self.clientid+',"msg_id":'+str(self.msgid)+',"psessionid":"'+self.psessionid+'"}'
        }
        req = urllib2.Request(url, data=urllib.urlencode(data_poll))
        req.add_header(
            'Referer', 'http://d.web2.qq.com/proxy.html?v=20130916001&callback=1&id=2')
        urllib2.urlopen(req)
        '''
        print 'sendto:',to_uin,'-',msg
        self.msgid+=1
        msg = u"[\""+ msg +u"\",[\"font\",{\"name\":\""+u'宋体'+u"\",\"size\":\"10\",\"style\":[0,0,0],\"color\":\"000000\"}]]"
        url = 'http://d.web2.qq.com/channel/send_buddy_msg2'
        a = {'to':to_uin,'face':180,'content':msg,'msg_id':self.msgid,'clientid':self.clientid,'psessionid':self.psessionid}
        array = {'r':json_encode.JSONEncoder().encode(a)}
        req = urllib2.Request(url, data=urllib.urlencode(array))
        req.add_header(
            'Referer', 'http://d.web2.qq.com/proxy.html?v=20130916001&callback=1&id=2')
        urllib2.urlopen(req) 
Example #3
Source File: json.py    From yosai with Apache License 2.0 5 votes vote down vote up
def register_custom_type(
            self, cls: type, marshaller: Optional[Callable[[Any], Any]] = default_marshaller,
            unmarshaller: Optional[Callable[[Any, Any], Any]] = default_unmarshaller, *,
            typename: str = None) -> None:
        typename = typename or qualified_name(cls)
        if marshaller:
            self._marshallers[cls] = typename, marshaller
            self.encoder_options['default'] = self._default_encoder
            self._encoder = JSONEncoder(**self.encoder_options)

        if unmarshaller:
            self._unmarshallers[typename] = cls, unmarshaller
            self.decoder_options['object_hook'] = self._custom_object_hook
            self._decoder = JSONDecoder(**self.decoder_options) 
Example #4
Source File: jsonconfig.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def get_encoder():
    return JSONEncoder(skipkeys=False, ensure_ascii=False,
        check_circular=True, allow_nan=True, indent=2, separators=(',', ': ')) 
Example #5
Source File: qqapi.py    From PyLinuxQQ with GNU General Public License v2.0 5 votes vote down vote up
def send_discuss_msg(self,did,msg=u'hello world'):
        print 'send discuss to:',did,'-',msg
        self.msgid+=1
        msg = u"[\""+ msg +u"\",[\"font\",{\"name\":\""+u'宋体'+u"\",\"size\":\"10\",\"style\":[0,0,0],\"color\":\"000000\"}]]"
        url = 'http://d.web2.qq.com/channel/send_discu_msg2'
        a = {'did':did,'face':180,'content':msg,'msg_id':self.msgid,'clientid':self.clientid,'psessionid':self.psessionid}
        array = {'r':json_encode.JSONEncoder().encode(a)}
        req = urllib2.Request(url, data=urllib.urlencode(array))
        req.add_header(
            'Referer', 'http://d.web2.qq.com/proxy.html?v=20130916001&callback=1&id=2')
        result=urllib2.urlopen(req).read()
        print 'dicus:',result 
Example #6
Source File: qqapi.py    From PyLinuxQQ with GNU General Public License v2.0 5 votes vote down vote up
def send_group_msg(self,gid,msg=u'hello world'):
        print 'send group to:',gid,'-',msg
        self.msgid+=1
        msg = u"[\""+ msg +u"\",[\"font\",{\"name\":\""+u'宋体'+u"\",\"size\":\"10\",\"style\":[0,0,0],\"color\":\"000000\"}]]"
        url = 'http://d.web2.qq.com/channel/send_qun_msg2'
        a = {'group_uin':gid,'face':180,'content':msg,'msg_id':self.msgid,'clientid':self.clientid,'psessionid':self.psessionid}
        array = {'r':json_encode.JSONEncoder().encode(a)}
        req = urllib2.Request(url, data=urllib.urlencode(array))
        req.add_header(
            'Referer', 'http://d.web2.qq.com/proxy.html?v=20130916001&callback=1&id=2')
        result=urllib2.urlopen(req).read()
        print 'group:',result 
Example #7
Source File: utils.py    From mplleaflet with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def iterencode(self, o, _one_shot=False):
        """Encode the given object and yield each string
        representation as available.
        For example::
            for chunk in JSONEncoder().iterencode(bigobject):
                mysocket.write(chunk)
        """
        c_make_encoder_original = json.encoder.c_make_encoder
        json.encoder.c_make_encoder = None

        if self.check_circular:
            markers = {}
        else:
            markers = None
        if self.ensure_ascii:
            _encoder = json.encoder.encode_basestring_ascii
        else:
            _encoder = json.encoder.encode_basestring

        def floatstr(o, allow_nan=self.allow_nan,
                     _repr=lambda x: format(x, self._formatter),
                     _inf=float("inf"), _neginf=-float("inf")):
            # Check for specials.  Note that this type of test is processor
            # and/or platform-specific, so do tests which don't depend on the
            # internals.
            if o != o:
                text = 'NaN'
            elif o == _inf:
                text = 'Infinity'
            elif o == _neginf:
                text = '-Infinity'
            else:
                return _repr(o)

            if not allow_nan:
                raise ValueError(
                    "Out of range float values are not JSON compliant: " +
                    repr(o))

            return text

        if (_one_shot and json.encoder.c_make_encoder is not None
                and self.indent is None):
            _iterencode = json.encoder.c_make_encoder(
                markers, self.default, _encoder, self.indent,
                self.key_separator, self.item_separator, self.sort_keys,
                self.skipkeys, self.allow_nan)
        else:
            _iterencode = json.encoder._make_iterencode(
                markers, self.default, _encoder, self.indent, floatstr,
                self.key_separator, self.item_separator, self.sort_keys,
                self.skipkeys, _one_shot)
        json.encoder.c_make_encoder = c_make_encoder_original
        return _iterencode(o, 0)