Convert field value pairs into regular message.

    Args:
      js: A JSON object to convert the field value pairs.
      message: A regular protocol message to record the data.

    Raises:
      ParseError: In case of problems converting.
10310
def _ConvertFieldValuePair(self, js, message):
    
    names = []
    message_descriptor = message.DESCRIPTOR
    fields_by_json_name = dict((f.json_name, f)
                               for f in message_descriptor.fields)
    for name in js:
      try:
        field = fields_by_json_name.get(name, None)
        if not field:
          field = message_descriptor.fields_by_name.get(name, None)
        if not field:
          if self.ignore_unknown_fields:
            continue
          raise ParseError(
              'Message type "{0}" has no field named "{1}".'.format(
                  message_descriptor.full_name, name))
        if name in names:
          raise ParseError('Message type "{0}" should not have multiple '
                           '"{1}" fields.'.format(
                               message.DESCRIPTOR.full_name, name))
        names.append(name)
        # Check no other oneof field is parsed.
        if field.containing_oneof is not None:
          oneof_name = field.containing_oneof.name
          if oneof_name in names:
            raise ParseError('Message type "{0}" should not have multiple '
                             '"{1}" oneof fields.'.format(
                                 message.DESCRIPTOR.full_name, oneof_name))
          names.append(oneof_name)

        value = js[name]
        if value is None:
          if (field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE
              and field.message_type.full_name == 'google.protobuf.Value'):
            sub_message = getattr(message, field.name)
            sub_message.null_value = 0
          else:
            message.ClearField(field.name)
          continue

        # Parse field value.
        if _IsMapEntry(field):
          message.ClearField(field.name)
          self._ConvertMapFieldValue(value, message, field)
        elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
          message.ClearField(field.name)
          if not isinstance(value, list):
            raise ParseError('repeated field {0} must be in [] which is '
                             '{1}.'.format(name, value))
          if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
            # Repeated message field.
            for item in value:
              sub_message = getattr(message, field.name).add()
              # None is a null_value in Value.
              if (item is None and
                  sub_message.DESCRIPTOR.full_name != 'google.protobuf.Value'):
                raise ParseError('null is not allowed to be used as an element'
                                 ' in a repeated field.')
              self.ConvertMessage(item, sub_message)
          else:
            # Repeated scalar field.
            for item in value:
              if item is None:
                raise ParseError('null is not allowed to be used as an element'
                                 ' in a repeated field.')
              getattr(message, field.name).append(
                  _ConvertScalarFieldValue(item, field))
        elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
          sub_message = getattr(message, field.name)
          sub_message.SetInParent()
          self.ConvertMessage(value, sub_message)
        else:
          setattr(message, field.name, _ConvertScalarFieldValue(value, field))
      except ParseError as e:
        if field and field.containing_oneof is None:
          raise ParseError('Failed to parse {0} field: {1}'.format(name, e))
        else:
          raise ParseError(str(e))
      except ValueError as e:
        raise ParseError('Failed to parse {0} field: {1}.'.format(name, e))
      except TypeError as e:
        raise ParseError('Failed to parse {0} field: {1}.'.format(name, e))
525207
def _AnyMessageToJsonObject(self, message):
    """"""
    if not message.ListFields():
      return {}
    # Must print @type first, use OrderedDict instead of {}
    js = OrderedDict()
    type_url = message.type_url
    js['@type'] = type_url
    sub_message = _CreateMessageFromTypeUrl(type_url)
    sub_message.ParseFromString(message.value)
    message_descriptor = sub_message.DESCRIPTOR
    full_name = message_descriptor.full_name
    if _IsWrapperMessage(message_descriptor):
      js['value'] = self._WrapperMessageToJsonObject(sub_message)
      return js
    if full_name in _WKTJSONMETHODS:
      js['value'] = methodcaller(_WKTJSONMETHODS[full_name][0],
                                 sub_message)(self)
      return js
    return self._RegularMessageToJsonObject(sub_message, js)
236234
function message(key, args) {
  if (typeof key !== 'string') throw new Error('Error message key must be a string');
  const msg = messages.get(key);
  if (!msg) throw new Error(`An invalid error message key was used: ${key}.`);
  if (typeof msg === 'function') return msg(...args);
  if (args === undefined || args.length === 0) return msg;
  args.unshift(msg);
  return String(...args);
}
1175060
def _DecodeUnknownMessages(message, encoded_message, pair_type):
    """"""
    field_type = pair_type.value.type
    new_values = []
    all_field_names = [x.name for x in message.all_fields()]
    for name, value_dict in six.iteritems(encoded_message):
        if name in all_field_names:
            continue
        value = PyValueToMessage(field_type, value_dict)
        if pair_type.value.repeated:
            value = _AsMessageList(value)
        new_pair = pair_type(key=name, value=value)
        new_values.append(new_pair)
    return new_values
1324034
function parseMessage(message) {
  var result = {};
  message.replace(/<xml>|<\/xml>/, '').replace(/<!\[CDATA\[(.*?)\]\]>/ig, '$1').replace(/<(\w+)>(.*?)<\/\1>/g, function (_, key, value) {
    key = key.replace(/(\w)/, function (str) { return str.toLowerCase();});
    result[key] = value;
  });

  return result;
}
517748
def _message_to_payload(cls, message):
        ''''''
        try:
            return json.loads(message.decode())
        except UnicodeDecodeError:
            message = 'messages must be encoded in UTF-8'
        except json.JSONDecodeError:
            message = 'invalid JSON'
        raise cls._error(cls.PARSE_ERROR, message, True, None)
256712
def _MessageToJsonObject(self, message):
    """"""
    message_descriptor = message.DESCRIPTOR
    full_name = message_descriptor.full_name
    if _IsWrapperMessage(message_descriptor):
      return self._WrapperMessageToJsonObject(message)
    if full_name in _WKTJSONMETHODS:
      return methodcaller(_WKTJSONMETHODS[full_name][0], message)(self)
    js = {}
    return self._RegularMessageToJsonObject(message, js)
378851
def convert_value(v):
    
    if v and isinstance(v, six.string_types):
        v = v.strip()
        if (v.startswith('{') and v.endswith('}')) or (v.startswith('[') and v.endswith(']')):
            try:
                return json.loads(v)
            except Exception as e:
                logger.error(e)

    return v
419655
function parseCustomValue(value, parse) {
  try {
    let parsed = parse(value)
    if (parsed === undefined) {
      return { value: null }
    }
    return { value: parsed }
  } catch (error) {
    return { error: error.message }
  }
}
984853
function (message, encoding) {
    return module.exports.jsonToObject(
      module.exports.decodePayload(message, encoding))
  }
215928
function _formatMessage(message, attribute, rule, parameters) {
    parameters.unshift(_getAttribute(attribute));

    for(i in parameters){
      message = message.replace(/:[a-zA-z_][a-zA-z_0-9]+/, parameters[i]);
    }

    if (typeof _replacers[rule] === 'function') {
      message = _replacers[rule](message, attribute, rule, parameters);
    }

    return message;
  }
957679
async def _dump_message_field(self, writer, msg, field, fvalue=None):
        
        fname, ftype, params = field[0], field[1], field[2:]
        fvalue = getattr(msg, fname, None) if fvalue is None else fvalue
        await self.dump_field(writer, fvalue, ftype, params)
121543
def _ValueMessageToJsonObject(self, message):
    """"""
    which = message.WhichOneof('kind')
    # If the Value message is not set treat as null_value when serialize
    # to JSON. The parse back result will be different from original message.
    if which is None or which == 'null_value':
      return None
    if which == 'list_value':
      return self._ListValueMessageToJsonObject(message.list_value)
    if which == 'struct_value':
      value = message.struct_value
    else:
      value = getattr(message, which)
    oneof_descriptor = message.DESCRIPTOR.fields_by_name[which]
    return self._FieldToJsonObject(oneof_descriptor, value)
241840
function parse_messages (parser_type, str) {
  var parser = new HTTPParser(parser_type);
  var buffer = new Buffer(str, 'utf-8');
  var output = [];

  parser.onMessageBegin = function() {
    output.push({
      versionMajor: undefined,
      versionMinor: undefined,
      method: undefined,
      uri: undefined,
      statusCode: undefined,
      headers: {},
      body: "",
      complete: false
    });
    parser.field = null;
    parser.value = null;
  };

  parser.onURL = function(b, start, len) {
    var slice = b.toString('ascii', start, start + len);
    if (output[output.length-1].url) {
      output[output.length-1].url += slice;
    } else {
      // Almost always will branch here.
      output[output.length-1].url = slice;
    }
  };
  
  parser.onHeaderField = function(b, start, len) {
    var slice = b.toString('ascii', start, start + len).toLowerCase();
    if (parser.value != undefined) {
      // note that this overwrites dup headers
      output[output.length-1].headers[parser.field] = parser.value;
      parser.field = null;
      parser.value = null;
    }
    if (parser.field) {
      parser.field += slice;
    } else {
      parser.field = slice;
    }
  };

  parser.onHeaderValue = function(b, start, len) {
    var slice = b.toString('ascii', start, start + len);
    if (parser.value) {
      parser.value += slice;
    } else {
      parser.value = slice;
    }
  };

  parser.onHeadersComplete = function(info) {
    if (parser.field && (parser.value != undefined)) {
      output[output.length-1].headers[parser.field] = parser.value;
      parser.field = null;
      parser.value = null;
    }

    output[output.length-1].versionMajor = info.versionMajor;
    output[output.length-1].versionMinor = info.versionMinor;
    output[output.length-1].statusCode = info.statusCode;
    output[output.length-1].method = info.method;

    return false // isHeadResponse;
  };

  parser.onBody = function(b, start, len) {
    var slice = b.slice(start, start + len);
    output[output.length-1].body += slice;
  };

  parser.onMessageComplete = function() {
    output[output.length-1].complete = true;
    if (parser.field && (parser.value != undefined)) {
      output[output.length-1].headers[parser.field] = parser.value;
    }  
  }
  
  parser.execute(buffer, 0, buffer.length);
  
  // filter out incomplete responses.
  var complete_output = [];
  output.forEach(function (o) {
    if (o.complete) {
      complete_output.push(o);
    }
  })
  return complete_output;
}
252303
def convert_loaded_json(js):
    
    if not isinstance(js, (Mapping, tuple, list)):
        return try_convert(js)
    try:
        return type(js)(convert_loaded_json(item) for item in js.iteritems())
    except:
        try:
            return type(js)(convert_loaded_json(item) for item in iter(js))
        except:
            return try_convert(js)
1022238
def from_message(cls, message):
        
        self = cls(json=message)
        try:
            decoded_data = json.loads(message)
        except ValueError:
            # Message is not a valid JSON. Return as invalid.
            return self
        try:
            report_data = decoded_data['csp-report']
        except KeyError:
            # Message is not a valid CSP report. Return as invalid.
            return self

        # Extract individual fields
        for report_name, field_name in REQUIRED_FIELD_MAP + OPTIONAL_FIELD_MAP:
            setattr(self, field_name, report_data.get(report_name))
        # Extract integer fields
        for report_name, field_name in INTEGER_FIELD_MAP:
            value = report_data.get(report_name)
            field = self._meta.get_field(field_name)
            min_value, max_value = connection.ops.integer_field_range(field.get_internal_type())
            if min_value is None:
                min_value = 0
            # All these fields are possitive. Value can't be negative.
            min_value = max(min_value, 0)
            if value is not None and min_value <= value and (max_value is None or value <= max_value):
                setattr(self, field_name, value)
        # Extract disposition
        disposition = report_data.get('disposition')
        if disposition in dict(DISPOSITIONS).keys():
            self.disposition = disposition

        # Check if report is valid
        is_valid = True
        for field_name in dict(REQUIRED_FIELD_MAP).values():
            if getattr(self, field_name) is None:
                is_valid = False
                break
        self.is_valid = is_valid

        return self
1152832
function handleFieldValue (value) {
      if (!(value instanceof Buffer || typeof value === 'string')) {
        if (is(value).a(Object)) {
          if (value instanceof fs.FileReadStream) {
            return value
          } else {
            return Unirest.serializers.json(value)
          }
        } else {
          return value.toString()
        }
      } else return value
    }