【问题标题】:Read nested data from json using .proto in python在python中使用.proto从json读取嵌套数据
【发布时间】:2021-12-10 11:55:37
【问题描述】:

我想从 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?)      

【问题讨论】:

  • 抱歉,这里的 proto 用例是什么?例如,单独反序列化 json 如何不能解决问题?
  • 把它想象成在 json 上运行一个 select sql 查询。

标签: json python-3.x protocol-buffers


【解决方案1】:

几件事:

  1. 类型为ListItems,但名称为EMPLOYEE_ADDRESS
  2. repeated 的 Python 很尴尬(!)
  3. 你写的代码比你需要的多
  4. 如果可以的话,我建议您遵守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)

【讨论】:

  • 我很高兴听到这个消息。如果有帮助,请考虑将此标记为答案,谢谢。
猜你喜欢
  • 1970-01-01
  • 2021-06-10
  • 2020-01-28
  • 1970-01-01
  • 2020-06-28
  • 2019-10-31
  • 1970-01-01
  • 2021-02-02
  • 1970-01-01
相关资源
最近更新 更多