当前位置: 首页>>代码示例>>Python>>正文


Python json_format.Parse方法代码示例

本文整理汇总了Python中google.protobuf.json_format.Parse方法的典型用法代码示例。如果您正苦于以下问题:Python json_format.Parse方法的具体用法?Python json_format.Parse怎么用?Python json_format.Parse使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在google.protobuf.json_format的用法示例。


在下文中一共展示了json_format.Parse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: add_comment

# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import Parse [as 别名]
def add_comment(self,
                  category,
                  message,
                  path,
                  start_line=0,
                  end_line=0,
                  start_char=0,
                  end_char=0,
                  suggestions=()):
    comment = Data.Comment()
    comment.category = category
    comment.message = message
    comment.path = path
    comment.start_line = start_line
    comment.end_line = end_line
    comment.start_char = start_char
    comment.end_char = end_char
    for s in suggestions:
      # Convert from dict to proto message by way of JSON.
      json_format.Parse(self.m.json.dumps(s), comment.suggestions.add())

    if comment not in self._comments:
      self._comments.append(comment) 
开发者ID:luci,项目名称:recipes-py,代码行数:25,代码来源:api.py

示例2: testSurrogates

# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import Parse [as 别名]
def testSurrogates(self):
    # Test correct surrogate handling.
    message = json_format_proto3_pb2.TestMessage()
    json_format.Parse('{"stringValue": "\\uD83D\\uDE01"}', message)
    self.assertEqual(message.string_value,
                     b'\xF0\x9F\x98\x81'.decode('utf-8', 'strict'))

    # Error case: unpaired high surrogate.
    self.CheckError(
        '{"stringValue": "\\uD83D"}',
        r'Invalid \\uXXXX escape|Unpaired.*surrogate')

    # Unpaired low surrogate.
    self.CheckError(
        '{"stringValue": "\\uDE01"}',
        r'Invalid \\uXXXX escape|Unpaired.*surrogate') 
开发者ID:ryfeus,项目名称:lambda-packs,代码行数:18,代码来源:json_format_test.py

示例3: testParseEnumValue

# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import Parse [as 别名]
def testParseEnumValue(self):
    message = json_format_proto3_pb2.TestMessage()
    text = '{"enumValue": 0}'
    json_format.Parse(text, message)
    text = '{"enumValue": 1}'
    json_format.Parse(text, message)
    self.CheckError(
        '{"enumValue": "baz"}',
        'Failed to parse enumValue field: Invalid enum value baz '
        'for enum type proto3.EnumType.')
    # Proto3 accepts numeric unknown enums.
    text = '{"enumValue": 12345}'
    json_format.Parse(text, message)
    # Proto2 does not accept unknown enums.
    message = unittest_pb2.TestAllTypes()
    self.assertRaisesRegex(
        json_format.ParseError,
        'Failed to parse optionalNestedEnum field: Invalid enum value 12345 '
        'for enum type protobuf_unittest.TestAllTypes.NestedEnum.',
        json_format.Parse, '{"optionalNestedEnum": 12345}', message) 
开发者ID:ryfeus,项目名称:lambda-packs,代码行数:22,代码来源:json_format_test.py

示例4: testInvalidIntegerValue

# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import Parse [as 别名]
def testInvalidIntegerValue(self):
    message = json_format_proto3_pb2.TestMessage()
    text = '{"int32Value": 0x12345}'
    self.assertRaises(json_format.ParseError,
                      json_format.Parse, text, message)
    self.CheckError('{"int32Value": 1.5}',
                    'Failed to parse int32Value field: '
                    'Couldn\'t parse integer: 1.5.')
    self.CheckError('{"int32Value": 012345}',
                    (r'Failed to load JSON: Expecting \'?,\'? delimiter: '
                     r'line 1.'))
    self.CheckError('{"int32Value": " 1 "}',
                    'Failed to parse int32Value field: '
                    'Couldn\'t parse integer: " 1 ".')
    self.CheckError('{"int32Value": "1 "}',
                    'Failed to parse int32Value field: '
                    'Couldn\'t parse integer: "1 ".')
    self.CheckError('{"int32Value": 12345678901234567890}',
                    'Failed to parse int32Value field: Value out of range: '
                    '12345678901234567890.')
    self.CheckError('{"uint32Value": -1}',
                    'Failed to parse uint32Value field: '
                    'Value out of range: -1.') 
开发者ID:ryfeus,项目名称:lambda-packs,代码行数:25,代码来源:json_format_test.py

示例5: testInvalidAny

# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import Parse [as 别名]
def testInvalidAny(self):
    message = any_pb2.Any()
    text = '{"@type": "type.googleapis.com/google.protobuf.Int32Value"}'
    self.assertRaisesRegex(
        KeyError,
        'value',
        json_format.Parse, text, message)
    text = '{"value": 1234}'
    self.assertRaisesRegex(
        json_format.ParseError,
        '@type is missing when parsing any message.',
        json_format.Parse, text, message)
    text = '{"@type": "type.googleapis.com/MessageNotExist", "value": 1234}'
    self.assertRaisesRegex(
        TypeError,
        'Can not find message descriptor by type_url: '
        'type.googleapis.com/MessageNotExist.',
        json_format.Parse, text, message)
    # Only last part is to be used: b/25630112
    text = (r'{"@type": "incorrect.googleapis.com/google.protobuf.Int32Value",'
            r'"value": 1234}')
    json_format.Parse(text, message) 
开发者ID:ryfeus,项目名称:lambda-packs,代码行数:24,代码来源:json_format_test.py

示例6: testPreservingProtoFieldNames

# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import Parse [as 别名]
def testPreservingProtoFieldNames(self):
    message = json_format_proto3_pb2.TestMessage()
    message.int32_value = 12345
    self.assertEqual('{\n  "int32Value": 12345\n}',
                     json_format.MessageToJson(message))
    self.assertEqual('{\n  "int32_value": 12345\n}',
                     json_format.MessageToJson(message, False, True))
    # When including_default_value_fields is True.
    message = json_format_proto3_pb2.TestTimestamp()
    self.assertEqual('{\n  "repeatedValue": []\n}',
                     json_format.MessageToJson(message, True, False))
    self.assertEqual('{\n  "repeated_value": []\n}',
                     json_format.MessageToJson(message, True, True))

    # Parsers accept both original proto field names and lowerCamelCase names.
    message = json_format_proto3_pb2.TestMessage()
    json_format.Parse('{"int32Value": 54321}', message)
    self.assertEqual(54321, message.int32_value)
    json_format.Parse('{"int32_value": 12345}', message)
    self.assertEqual(12345, message.int32_value) 
开发者ID:ryfeus,项目名称:lambda-packs,代码行数:22,代码来源:json_format_test.py

示例7: get_summary_description

# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import Parse [as 别名]
def get_summary_description(node_def):
  """Given a TensorSummary node_def, retrieve its SummaryDescription.

  When a Summary op is instantiated, a SummaryDescription of associated
  metadata is stored in its NodeDef. This method retrieves the description.

  Args:
    node_def: the node_def_pb2.NodeDef of a TensorSummary op

  Returns:
    a summary_pb2.SummaryDescription

  Raises:
    ValueError: if the node is not a summary op.
  """

  if node_def.op != 'TensorSummary':
    raise ValueError("Can't get_summary_description on %s" % node_def.op)
  description_str = _compat.as_str_any(node_def.attr['description'].s)
  summary_description = SummaryDescription()
  _json_format.Parse(description_str, summary_description)
  return summary_description 
开发者ID:ryfeus,项目名称:lambda-packs,代码行数:24,代码来源:summary.py

示例8: testJsonEscapeString

# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import Parse [as 别名]
def testJsonEscapeString(self):
    message = json_format_proto3_pb2.TestMessage()
    if sys.version_info[0] < 3:
      message.string_value = '&\n<\"\r>\b\t\f\\\001/\xe2\x80\xa8\xe2\x80\xa9'
    else:
      message.string_value = '&\n<\"\r>\b\t\f\\\001/'
      message.string_value += (b'\xe2\x80\xa8\xe2\x80\xa9').decode('utf-8')
    self.assertEqual(
        json_format.MessageToJson(message),
        '{\n  "stringValue": '
        '"&\\n<\\\"\\r>\\b\\t\\f\\\\\\u0001/\\u2028\\u2029"\n}')
    parsed_message = json_format_proto3_pb2.TestMessage()
    self.CheckParseBack(message, parsed_message)
    text = u'{"int32Value": "\u0031"}'
    json_format.Parse(text, message)
    self.assertEqual(message.int32_value, 1) 
开发者ID:abhisuri97,项目名称:auto-alt-text-lambda-api,代码行数:18,代码来源:json_format_test.py

示例9: testInvalidMap

# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import Parse [as 别名]
def testInvalidMap(self):
    message = json_format_proto3_pb2.TestMap()
    text = '{"int32Map": {"null": 2, "2": 3}}'
    self.assertRaisesRegexp(
        json_format.ParseError,
        'Failed to parse int32Map field: invalid literal',
        json_format.Parse, text, message)
    text = '{"int32Map": {1: 2, "2": 3}}'
    self.assertRaisesRegexp(
        json_format.ParseError,
        (r'Failed to load JSON: Expecting property name'
         r'( enclosed in double quotes)?: line 1'),
        json_format.Parse, text, message)
    text = '{"boolMap": {"null": 1}}'
    self.assertRaisesRegexp(
        json_format.ParseError,
        'Failed to parse boolMap field: Expected "true" or "false", not null.',
        json_format.Parse, text, message)
    if sys.version_info < (2, 7):
      return
    text = r'{"stringMap": {"a": 3, "\u0061": 2}}'
    self.assertRaisesRegexp(
        json_format.ParseError,
        'Failed to load JSON: duplicate key a',
        json_format.Parse, text, message) 
开发者ID:abhisuri97,项目名称:auto-alt-text-lambda-api,代码行数:27,代码来源:json_format_test.py

示例10: testInvalidAny

# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import Parse [as 别名]
def testInvalidAny(self):
    message = any_pb2.Any()
    text = '{"@type": "type.googleapis.com/google.protobuf.Int32Value"}'
    self.assertRaisesRegexp(
        KeyError,
        'value',
        json_format.Parse, text, message)
    text = '{"value": 1234}'
    self.assertRaisesRegexp(
        json_format.ParseError,
        '@type is missing when parsing any message.',
        json_format.Parse, text, message)
    text = '{"@type": "type.googleapis.com/MessageNotExist", "value": 1234}'
    self.assertRaisesRegexp(
        TypeError,
        'Can not find message descriptor by type_url: '
        'type.googleapis.com/MessageNotExist.',
        json_format.Parse, text, message)
    # Only last part is to be used: b/25630112
    text = (r'{"@type": "incorrect.googleapis.com/google.protobuf.Int32Value",'
            r'"value": 1234}')
    json_format.Parse(text, message) 
开发者ID:abhisuri97,项目名称:auto-alt-text-lambda-api,代码行数:24,代码来源:json_format_test.py

示例11: __init__

# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import Parse [as 别名]
def __init__(self, json_path: str, auto_update=True, dry_run=False):
        self.json_path = json_path if json_path.endswith('.json') else json_path + '.json'
        self.json_path = os.path.abspath(os.path.expanduser(os.path.expandvars(self.json_path)))
        self.ckpt_path = os.path.splitext(self.json_path)[0]
        self.dry_run = dry_run

        # do not parse as proto, since some parameters might have changed
        with open(self.json_path, 'r') as f:
            self.json = json.load(f)

            self.version = self.json['version'] if 'version' in self.json else 0

        if self.version != Checkpoint.VERSION:
            if auto_update:
                self.update_checkpoint()
            else:
                raise Exception("Version of checkpoint is {} but {} is required. Please upgrade the model or "
                                "set the auto update flag.".format(self.version, Checkpoint.VERSION))

        else:
            print("Checkpoint version {} is up-to-date.".format(self.version))

        with open(self.json_path, 'r') as f:
            self.checkpoint = json_format.Parse(f.read(), CheckpointParams()) 
开发者ID:Calamari-OCR,项目名称:calamari,代码行数:26,代码来源:checkpoint.py

示例12: _load_sample

# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import Parse [as 别名]
def _load_sample(self, sample):
        gt_txt_path = sample['pred_path']
        if gt_txt_path is None:
            return None, None

        if gt_txt_path.endswith('.json'):
            with codecs.open(gt_txt_path, 'r', 'utf-8') as f:
                p = Parse(str(f.read()), Predictions())
                if len(p.predictions) == 0:
                    return None, None

                voted_p = p.predictions[0]
                for vp in p.predictions:
                    if vp.id == 'voted':
                        voted_p = vp

                sample['best_prediction'] = voted_p
                sample['predictions'] = p

                return None, voted_p.sentence 
开发者ID:Calamari-OCR,项目名称:calamari,代码行数:22,代码来源:extended_prediction_dataset.py

示例13: from_json

# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import Parse [as 别名]
def from_json(cls, options_json: Text) -> 'StatsOptions':
    """Construct an instance of stats options from a JSON representation.

    Args:
      options_json: A JSON representation of the __dict__ attribute of a
        StatsOptions instance.

    Returns:
      A StatsOptions instance constructed by setting the __dict__ attribute to
      the deserialized value of options_json.
    """
    options_dict = json.loads(options_json)
    if 'schema_json' in options_dict:
      options_dict['_schema'] = json_format.Parse(options_dict['schema_json'],
                                                  schema_pb2.Schema())
      del options_dict['schema_json']
    options = cls()
    options.__dict__ = options_dict
    return options 
开发者ID:tensorflow,项目名称:data-validation,代码行数:21,代码来源:stats_options.py

示例14: __call__

# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import Parse [as 别名]
def __call__(self, stream, content_type):
        """
        Args:
            stream:
            content_type:
        """
        try:
            data = stream.read()
        finally:
            stream.close()

        for possible_response in _possible_responses():
            try:
                return protobuf_to_dict(json_format.Parse(data, possible_response()))
            except (UnicodeDecodeError, DecodeError, json_format.ParseError):
                # given that the payload does not have the response type, there no way to infer
                # the response without keeping state, so I'm iterating all the options.
                pass
        return json.loads(data.decode()) 
开发者ID:aws,项目名称:sagemaker-python-sdk,代码行数:21,代码来源:predictor.py

示例15: end_of_rib

# 需要导入模块: from google.protobuf import json_format [as 别名]
# 或者: from google.protobuf.json_format import Parse [as 别名]
def end_of_rib(self, id=None, table_id=None, json=None):
        '''
            Constructs EndOfRib message.


        '''

        if json:
            msg = json_format.Parse(json, rib.ModifyRequest.Request())
        else:
            if not id:
                id = self.request_id()
            msg = rib.ModifyRequest.Request(id=id,
                                                END_OF_RIB=rib.EndOfRib(id=table_id))
        self.request[id] = msg
        return msg.id 
开发者ID:nokia,项目名称:SROS-grpc-services,代码行数:18,代码来源:rib_api_service.py


注:本文中的google.protobuf.json_format.Parse方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。