Takes a ProtoBuf Message obj and convertes it to a dict.
777658
def pb2dict(obj):
    
    adict = {}
    if not obj.IsInitialized():
        return None
    for field in obj.DESCRIPTOR.fields:
        if not getattr(obj, field.name):
            continue
        if not field.label == FD.LABEL_REPEATED:
            if not field.type == FD.TYPE_MESSAGE:
                adict[field.name] = getattr(obj, field.name)
            else:
                value = pb2dict(getattr(obj, field.name))
                if value:
                    adict[field.name] = value
        else:
            if field.type == FD.TYPE_MESSAGE:
                adict[field.name] = \
                    [pb2dict(v) for v in getattr(obj, field.name)]
            else:
                adict[field.name] = [v for v in getattr(obj, field.name)]
    return adict
163902
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'output' in _dict:
            args['output'] = MessageOutput._from_dict(_dict.get('output'))
        else:
            raise ValueError(
                'Required property \'output\' not present in MessageResponse JSON'
            )
        if 'context' in _dict:
            args['context'] = MessageContext._from_dict(_dict.get('context'))
        return cls(**args)
1084362
def to_json(obj):
    
    try:
        return json.dumps(obj, default=lambda obj: {k.lower(): v for k, v in obj.__dict__.items()},
                          sort_keys=False, separators=(',', ':')).encode()
    except Exception as e:
        logger.info("to_json: ", e, obj)
494443
def sobject_to_json(obj, key_to_lower=False):
    
    import json
    data = sobject_to_dict(obj, key_to_lower=key_to_lower, json_serialize=True)
    return json.dumps(data)
1117344
def to_dict(self):
        """"""
        as_dict = dict(self.payload or ())
        as_dict['message'] = self.message
        return as_dict
1197566
def to_dict(self):
        
        output = {}
        for key, value in self.__dict__['p'].iteritems():
            if value is None or isinstance(value, SIMPLE_TYPES):
                output[key] = value
            elif hasattr(value, 'to_dot'):
                output[key] = value.to_dot()
            elif hasattr(value, 'to_dict'):
                output[key] = value.to_dict()
            elif isinstance(value, datetime.date):
                # Convert date/datetime to ms-since-epoch ("new Date()").
                ms = time.mktime(value.utctimetuple()) * 1000
                ms += getattr(value, 'microseconds', 0) / 1000
                output[key] = int(ms)
            elif isinstance(value, dict):
                output[key] = []
            else:
                raise ValueError('cannot encode ' + repr(key))

        return output
1024568
def as_dict(self):
        
        out = {}
        for prop in self:
            propval = getattr(self, prop)

            if hasattr(propval, 'for_json'):
                out[prop] = propval.for_json()
            elif isinstance(propval, list):
                out[prop] = [getattr(x, 'for_json', lambda:x)() for x in propval]
            elif isinstance(propval, (ProtocolBase, LiteralValue)):
                out[prop] = propval.as_dict()
            elif propval is not None:
                out[prop] = propval

        return out
437132
def object_to_dict(obj):
    '''
    
    '''
    if isinstance(obj, list) or isinstance(obj, tuple):
        ret = []
        for item in obj:
            ret.append(object_to_dict(item))
    elif hasattr(obj, '__dict__'):
        ret = {}
        for item in obj.__dict__:
            if item.startswith('_'):
                continue
            ret[item] = object_to_dict(obj.__dict__[item])
    else:
        ret = obj
    return ret
441154
def to_protobuf(self):
        """"""
        self._validate()
        kwargs = {k: _convert(getattr(self, k), 'to_protobuf')
                  for k in self._get_params()}
        return self._protobuf_cls(**kwargs)
1152995
def namespace_to_dict(obj):
    
    if isinstance(obj, (argparse.Namespace, optparse.Values)):
        return vars(obj)
    return obj
1142719
def dict_from_object(obj: object):
    """"""

    # If object is a dict instance, no need to convert.
    return (obj if isinstance(obj, dict)
            else {attr: getattr(obj, attr)
                  for attr in dir(obj) if not attr.startswith('_')})
1190339
def to_dict(self):
        """"""
        val = dict(self.payload or ())
        if self.message:
            val['message'] = self.message
        return val
7442
def __obj2json(self, obj):
        
        return json.dumps(obj, indent=self._indent, sort_keys=self._sort_keys)
855506
def _elements_to_dict(data, position, obj_end, opts, result=None):
    """"""
    if result is None:
        result = opts.document_class()
    end = obj_end - 1
    while position < end:
        key, value, position = _element_to_dict(data, position, obj_end, opts)
        result[key] = value
    if position != obj_end:
        raise InvalidBSON('bad object or element length')
    return result
582820
def _to_dict(self):
        """"""
        _dict = {}
        if hasattr(self, 'message_type') and self.message_type is not None:
            _dict['message_type'] = self.message_type
        if hasattr(self, 'text') and self.text is not None:
            _dict['text'] = self.text
        if hasattr(self, 'options') and self.options is not None:
            _dict['options'] = self.options._to_dict()
        if hasattr(self, 'intents') and self.intents is not None:
            _dict['intents'] = [x._to_dict() for x in self.intents]
        if hasattr(self, 'entities') and self.entities is not None:
            _dict['entities'] = [x._to_dict() for x in self.entities]
        if hasattr(self, 'suggestion_id') and self.suggestion_id is not None:
            _dict['suggestion_id'] = self.suggestion_id
        return _dict
518760
def dict_to_object(self, obj):  # pylint: disable=no-self-use
        """"""
        if not isinstance(obj, dict):
            return obj
        if 'sensor_id' in obj:
            sensor = Sensor(obj['sensor_id'])
            for key, val in obj.items():
                setattr(sensor, key, val)
            return sensor
        if all(k in obj for k in ['id', 'type', 'values']):
            child = ChildSensor(
                obj['id'], obj['type'], obj.get('description', ''))
            child.values = obj['values']
            return child
        if all(k.isdigit() for k in obj.keys()):
            return {int(k): v for k, v in obj.items()}
        return obj
294890
def toJson(protoObject, indent=None):
    
    # Using the internal method because this way we can reformat the JSON
    js = json_format.MessageToDict(protoObject, False)
    return json.dumps(js, indent=indent)