使用 python 中的 .proto 从 json 中读取嵌套数据

Read nested data from json using .proto in python

我想从 json 中读取嵌套数据。我已经基于 json 创建了一个 .proto 文件,但我仍然无法从 json.

中读取嵌套数据

nested.proto --> 使用 protoc --python_out=$PWD nested.proto

编译
syntax = "proto2";


message Employee{
    required int32 EMPLOYEE_ID = 1;
    
    message ListItems {
        required string FULLADDRESS = 1;
    }

    repeated ListItems EMPLOYEE_ADDRESS = 2;

}

nested.json

{
    "EMPLOYEE_ID": 5044,
    "EMPLOYEE_ADDRESS": [
        {
            "FULLADDRESS": "Suite 762"
        }
    ]
}

parse.py


#!/usr/bin/env python3

import json
from google.protobuf.json_format import Parse

import nested_pb2 as np


input_file = "nested.json"


if __name__ == "__main__":
    # reading json file
    f = open(input_file, 'rb')
    content = json.load(f)
    # initialize emp_table here
    emp_table = np.Employee()

    employee = Parse(json.dumps(content), emp_table, True)
    print(employee.EMPLOYEE_ID) #output: 5044
    
    
    emp_table = np.Employee().ListItems()
    
    
    items = Parse(json.dumps(content), emp_table, True)
    
    print(items.FULLADDRESS) #output: NO OUTPUT (WHY?)      

两件事:

  1. 类型是 ListItems 但名称是 EMPLOYEE_ADDRESS
  2. Python 与 repeated
  3. 很尴尬 (!)
  4. 您编写的代码超出了您的需要
  5. 如果可以,我建议您遵守 style guide

尝试:

#!/usr/bin/env python3

import json
from google.protobuf.json_format import Parse

import nested_pb2 as np

input_file = "nested.json"

if __name__ == "__main__":
    # reading json file
    f = open(input_file, 'rb')
    content = json.load(f)
    # initialize emp_table here
    emp_table = np.Employee()

    employee = Parse(json.dumps(content), emp_table, True)
    print(employee.EMPLOYEE_ID) #output: 5044

    for item in employee.EMPLOYEE_ADDRESS:
        print(item)