convert google.protobuf.descriptor instance to JSON string
516361
def pb2json(pb, useFieldNumber=False):
    '''  '''
    js = {}
    # fields = pb.DESCRIPTOR.fields #all fields
    fields = pb.ListFields()        #only filled (including extensions)
    for field,value in fields:
        if useFieldNumber:
            key = field.number
        else:
            key = field.name
        if field.type == FD.TYPE_MESSAGE:
            ftype = partial(pb2json, useFieldNumber=useFieldNumber)
        elif field.type in _ftype2js:
            ftype = _ftype2js[field.type]
        else:
            raise ParseError("Field %s.%s of type '%d' is not supported" % (pb.__class__.__name__, field.name, field.type, ))
        if field.label == FD.LABEL_REPEATED:
            js_value = []
            for v in value:
                js_value.append(ftype(v))
        else:
            js_value = ftype(value)
        js[key] = js_value
    return js
753810
function Convert (proto, a) {
  if (a instanceof Buffer) {
    return Convert.toString(proto, a)
  } else {
    return Convert.toBuffer(proto, a)
  }
}
445102
public <T> T read(final String s, final DataTypeDescriptor<T> descriptor) {
		try {
			return jsonFormat.read(s, descriptor);
		} catch (Exception e) {
			throw propagate(e);
		}
	}
40121
def _protobuf_value_to_string(value):
  
  value_in_json = json_format.MessageToJson(value)
  if value.HasField("string_value"):
    # Remove the quotations.
    return value_in_json[1:-1]
  return value_in_json
800800
public static Message fromJson(Message.Builder builder, JsonObject input) throws Exception {
    Descriptors.Descriptor descriptor = builder.getDescriptorForType();
    for (Map.Entry<String, JsonElement> entry : input.entrySet()) {
      String protoName = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, entry.getKey());
      Descriptors.FieldDescriptor field = descriptor.findFieldByName(protoName);
      if (field == null) {
        throw new Exception("Can't find descriptor for field " + protoName);
      }
      if (field.isRepeated()) {
        if (!entry.getValue().isJsonArray()) {
          // fail
        }
        JsonArray array = entry.getValue().getAsJsonArray();
        for (JsonElement item : array) {
          builder.addRepeatedField(field, parseField(field, item, builder));
        }
      } else {
        builder.setField(field, parseField(field, entry.getValue(), builder));
      }
    }
    return builder.build();
  }
1113867
def to_json(self):
        
        if self.type == FUSION:
            return self._fusion_to_json()

        if self.type == FRAGMENT:
            return fragment(
                start=int_or_str(self.p3_start),
                stop=int_or_str(self.p3_stop),
            )

        if self.type == HGVS:
            return hgvs(str(self.variantString))

        if self.type == GMOD:
            return gmod(
                namespace=self.identifier.namespace.keyword,
                name=self.identifier.name,
                identifier=self.identifier.identifier,
            )

        if self.type == PMOD:
            return pmod(
                namespace=self.identifier.namespace.keyword,
                name=self.identifier.name,
                identifier=self.identifier.identifier,
                code=self.residue,
                position=self.position
            )

        raise TypeError('unhandled type ({}) for modification {}'.format(self.type, self))
1113666
def proto_to_dict(message):
    
    if not isinstance(message, _ProtoMessageType):
        raise TypeError("Expected `message` to be a instance of protobuf message")

    data = {}

    for desc, field in message.ListFields():
        if desc.type == desc.TYPE_MESSAGE:
            if desc.label == desc.LABEL_REPEATED:
                data[desc.name] = list(map(proto_to_dict, field))
            else:
                data[desc.name] = proto_to_dict(field)
        else:
            data[desc.name] = list(field) if desc.label == desc.LABEL_REPEATED else field

    return data
114420
function serializeToJRD(descriptor) {
  var obj = {};
  if (descriptor.expires) { obj.expires = xsdDateTimeString(descriptor.expires); }
  if (descriptor.subject) { obj.subject = descriptor.subject; }
  if (descriptor.aliases.length > 0) {
    obj.aliases = [];
    descriptor.aliases.forEach(function(alias) {
      obj.aliases.push(alias);
    });
  }
  
  if (descriptor.properties.length > 0) {
    obj.properties = {};
    descriptor.properties.forEach(function(key, value) {
      obj.properties[key] = value;
    }, { flatten: true });
  }
  
  if (descriptor.links.length > 0) {
    obj.links = [];
    descriptor.links.forEach(function(link) {
      var l = {};
      if (link.rel) { l.rel = link.rel; }
      if (link.href) { l.href = link.href; }
      if (link.template) { l.template = link.template; }
      if (link.type) { l.type = link.type; }
      
      if (link.titles.length > 0) {
        l.titles = {};
        link.titles.forEach(function(lang, title) {
          if (lang === '_') {
            l.titles['default'] = title;
          } else {
            l.titles[lang] = title;
          }
        }, { flatten: true });
      }
      
      if (link.properties.length > 0) {
        l.properties = {};
        link.properties.forEach(function(key, value) {
          l.properties[key] = value;
        }, { flatten: true });
      }
      
      obj.links.push(l);
    });
  }
  
  return JSON.stringify(obj);
}
1051407
def switch_to_json_payload_encoding(call_fn, response_class):
    
    def json_serializer(*args, **kwargs):
        return bytes(json_format.MessageToJson(args[0], True, preserving_proto_field_name=True), "utf-8")
    def json_deserializer(*args, **kwargs):
        resp = response_class()
        json_format.Parse(args[0], resp, True)
        return resp
    call_fn._request_serializer    = json_serializer
    call_fn._response_deserializer = json_deserializer
233331
function lookupDescriptor(proto, key) {
		if (proto.hasOwnProperty(key)) {
			return Object.getOwnPropertyDescriptor(proto, key);
		} else if ((proto = Object.getPrototypeOf(proto))) {
			return lookupDescriptor(proto, key);
		} else {
			return null;
		}
	}
1010052
def to_json(self):
    
    return {self.NAMESPACE_RANGE_PARAM: self.ns_range.to_json_object(),
            self.BATCH_SIZE_PARAM: self._batch_size}
729706
def _bytes_generator(descriptor, max_length=0, limit=0):
    ''
    strs = values.get_strings(max_length, limit)
    vals = [bytes(_, 'utf-8') for _ in strs]
    return gen.IterValueGenerator(descriptor.name, vals)
130510
def fromJSON(value):
        
        j = json.loads(value)
        v = GPRasterData()
        if "defaultValue" in j:
            v.value = j['defaultValue']
        else:
            v.value = j['value']
        if 'paramName' in j:
            v.paramName = j['paramName']
        elif 'name' in j:
            v.paramName = j['name']
        return v
1060128
def _deserialize(cls, json_body, get_value_and_type):
        

        instance = cls()
        is_set = False
        properties = cls._get_property_names(instance)

        def get_property_detail(name):
            p = [p for p in instance._property_details if p.name == name or p.field_name == name]
            return None if len(p) == 0 else p[0]

        for k in json_body:
            field = json_body[k]
            pd = get_property_detail(k)
            pn = k if not pd else pd.to_property_name(k)
            if pn in properties:
                v, t = get_value_and_type(field)
                initial_value = getattr(instance, pn)
                value = instance._field_to_property(v, t, pd, initial_value)
                setattr(instance, pn, value)
                is_set = True

        return instance if is_set else None
1354140
def fromJSON(value):
        
        j = json.loads(value)
        v = GPRecordSet()
        if "defaultValue" in j:
            v.value = j['defaultValue']
        else:
            v.value = j['value']
        if 'paramName' in j:
            v.paramName = j['paramName']
        elif 'name' in j:
            v.paramName = j['name']
        return v
626923
def _prototype_to_generator(descriptor, cls):
    ''
    _fd = D.FieldDescriptor
    generator = None

    ints32 = [_fd.TYPE_INT32, _fd.TYPE_UINT32, _fd.TYPE_FIXED32,
              _fd.TYPE_SFIXED32, _fd.TYPE_SINT32]
    ints64 = [_fd.TYPE_INT64, _fd.TYPE_UINT64, _fd.TYPE_FIXED64,
              _fd.TYPE_SFIXED64, _fd.TYPE_SINT64]
    ints_signed = [_fd.TYPE_INT32, _fd.TYPE_SFIXED32, _fd.TYPE_SINT32,
                   _fd.TYPE_INT64, _fd.TYPE_SFIXED64, _fd.TYPE_SINT64]

    if descriptor.type in ints32+ints64:
        bitwidth = [32, 64][descriptor.type in ints64]
        unsigned = descriptor.type not in ints_signed
        generator = _int_generator(descriptor, bitwidth, unsigned)
    elif descriptor.type == _fd.TYPE_DOUBLE:
        generator = _float_generator(descriptor, 64)
    elif descriptor.type == _fd.TYPE_FLOAT:
        generator = _float_generator(descriptor, 32)
    elif descriptor.type == _fd.TYPE_STRING:
        generator = _string_generator(descriptor)
    elif descriptor.type == _fd.TYPE_BYTES:
        generator = _bytes_generator(descriptor)
    elif descriptor.type == _fd.TYPE_BOOL:
        generator = gen.IterValueGenerator(descriptor.name, [True, False])
    elif descriptor.type == _fd.TYPE_ENUM:
        generator = _enum_generator(descriptor)
    elif descriptor.type == _fd.TYPE_MESSAGE:
        generator = descriptor_to_generator(descriptor.message_type, cls)
        generator.set_name(descriptor.name)
    else:
        raise RuntimeError("type {} unsupported".format(descriptor.type))

    return generator
1323756
def convert_protodef_to_editable(proto):
    
    class Editable(object):
        def __init__(self, prot):
            self.kind = type(prot)
            self.name = prot.name
            self.comment = ""
            self.options = dict([(key.name, value) for (key, value) in prot.options.ListFields()])
            if isinstance(prot, EnumDescriptorProto):
                self.value = [convert_protodef_to_editable(x) for x in prot.value]
            elif isinstance(prot, DescriptorProto):
                self.field = [convert_protodef_to_editable(x) for x in prot.field]
                self.enum_type = [convert_protodef_to_editable(x) for x in prot.enum_type]
                self.nested_type = prot.nested_type
                self.oneof_decl = prot.oneof_decl
            elif isinstance(prot, EnumValueDescriptorProto):
                self.number = prot.number
            elif isinstance(prot, FieldDescriptorProto):
                if prot.type in [11, 14]:
                    self.ref_type = prot.type_name[1:]
                self.type = prot.type
                self.label = prot.label
            elif isinstance(prot, ServiceDescriptorProto):
                self.method = [convert_protodef_to_editable(x) for x in prot.method]
            elif isinstance(prot, MethodDescriptorProto):
                self.input_type = prot.input_type
                self.output_type = prot.output_type
            else:
                raise Exception, type(prot)

    return Editable(proto)