OLD | NEW |
(Empty) | |
| 1 # Copyright 2015 The Chromium Authors. All rights reserved. |
| 2 # Use of this source code is governed by a BSD-style license that can be |
| 3 # found in the LICENSE file. |
| 4 |
| 5 import logging |
| 6 |
| 7 from google.protobuf.descriptor import FieldDescriptor as fd |
| 8 |
| 9 def convert(pb): |
| 10 """Convert protobuf to plain-old-python-object""" |
| 11 obj = {} |
| 12 for field, value in pb.ListFields(): |
| 13 if field.label == fd.LABEL_REPEATED: |
| 14 obj[field.name] = list(_get_json_func(field.type)(v) for v in value) |
| 15 else: |
| 16 obj[field.name] = _get_json_func(field.type)(value) |
| 17 return obj |
| 18 |
| 19 def _get_json_func(field_type): |
| 20 if field_type in _FD_TO_JSON: |
| 21 return _FD_TO_JSON[field_type] |
| 22 else: |
| 23 logging.warning("pb_to_popo doesn't support converting %s", field_type) |
| 24 return unicode |
| 25 |
| 26 _FD_TO_JSON = { |
| 27 fd.TYPE_BOOL: bool, |
| 28 fd.TYPE_DOUBLE: float, |
| 29 fd.TYPE_ENUM: int, |
| 30 fd.TYPE_FIXED32: float, |
| 31 fd.TYPE_FIXED64: float, |
| 32 fd.TYPE_FLOAT: float, |
| 33 fd.TYPE_INT32: int, |
| 34 fd.TYPE_INT64: long, |
| 35 fd.TYPE_SFIXED32: float, |
| 36 fd.TYPE_SFIXED64: float, |
| 37 fd.TYPE_SINT32: int, |
| 38 fd.TYPE_SINT64: long, |
| 39 fd.TYPE_STRING: unicode, |
| 40 fd.TYPE_UINT32: int, |
| 41 fd.TYPE_UINT64: long, |
| 42 fd.TYPE_MESSAGE: convert |
| 43 } |
OLD | NEW |