首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用python中的.proto读取json中的嵌套数据

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

Stack Overflow用户
提问于 2021-12-10 11:55:37
回答 1查看 263关注 0票数 1

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

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

代码语言:javascript
运行
复制
syntax = "proto2";


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

    repeated ListItems EMPLOYEE_ADDRESS = 2;

}

nested.json

代码语言:javascript
运行
复制
{
    "EMPLOYEE_ID": 5044,
    "EMPLOYEE_ADDRESS": [
        {
            "FULLADDRESS": "Suite 762"
        }
    ]
}

parse.py

代码语言:javascript
运行
复制
#!/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?)      
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-12-10 17:25:02

几件事:

  1. 类型为ListItems,但名称为EMPLOYEE_ADDRESS
  2. Python很尴尬(!)用repeated's
  3. 你写的代码比你需要的要多
  4. 如果可以的话,我建议您加入style guide

尝试:

代码语言:javascript
运行
复制
#!/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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70304140

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档