Go map转json

今天分享的知识是 Go 接口。如果本文对你有帮助,不妨点个赞,如果你是 Go 语言初学者,不妨点个关注,一起成长一起进步,如果本文有错误的地方,欢迎指出!

但当有的场景,要返回哪些字段不确定时,就无法使用struct的方式。 还可以用map

python 复制代码
package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	Map2Json()
}

func Map2Json() {
	mapInstance := make(map[string]interface{})

	mapInstance["Name"] = "cs"
	mapInstance["Age"] = 28
	mapInstance["Address"] = "杭州"

	relation := make(map[string]interface{})

	relation["father"] = "cuixxxxxxx"
	relation["mother"] = "yinxxxxx"
	relation["wife"] = "pengxx"

	mapInstance["Relation"] = relation

	pet := make(map[string]interface{})
	pet["one"] = "弥弥懵"
	pet["two"] = "黄橙橙"
	pet["three"] = "呆呆"
	pet["four"] = "皮瓜瓜"
	pet["five"] = "斑斑"

	mapInstance["Cat"] = pet

	jsonStr, err := json.Marshal(mapInstance)

	fmt.Println("err is:", err)
	fmt.Println("jsonStr is:", string(jsonStr))
}

输出为:

python 复制代码
err is: <nil>
jsonStr is: {"Address":"杭州","Age":28,"Cat":{"five":"斑斑","four":"皮瓜瓜","one":"弥弥懵","three":"呆呆","two":"黄橙橙"},"Name":"cs","Relation":{"father":"cuixxxxxxx","mother":"yinxxxxx","wife":"pengxx"}}


在proto中如何定义这样的返回值?

如果使用proto来定义接口,如何定义不确定字段名称和数量的返回值?

即上面的 jsonStr,如何定义才能返回给前端?

尝试使用过Any,发现不行(Any的"风评"很不好,介绍时一般和one of出现在一起)

几经探求,发现这种情况该用Struct(或说Value)类型

Is "google/protobuf/struct.proto" the best way to send dynamic JSON over GRPC?\](stackoverflow.com/questions/5... "Is "google/protobuf/struct.proto" the best way to send dynamic JSON over GRPC?") **xxxx.proto:** ```python syntax = "proto3"; package demo; import "validate/validate.proto"; import "google/api/annotations.proto"; import "google/protobuf/timestamp.proto"; //import "google/protobuf/any.proto"; import "google/protobuf/struct.proto"; rpc Getxxxxx(GetxxxxxReq) returns (GetxxxxxResp) { option (google.api.http) = { get:"/api/v1/xxxx/xxxx/xxxxxx" }; } message GetxxxxxResp { google.protobuf.Value data = 1; } message GetxxxxxReq { // 用户名 string user_name = 1 [(validate.rules).string.max_len = 100, (validate.rules).string.min_len = 1]; // 创建时间 google.protobuf.Timestamp create_time = 2; } ``` xxxx.go 大致代码如下: ```python ar rs xxxxx mapInstance["default"] = mapDefault jsonByteSli, err := json.Marshal(mapInstance) v := &structpb.Value{} err = protojson.Unmarshal(jsonByteSli, v) rs.Data = v return &rs, nil ```

相关推荐
钮钴禄·爱因斯晨5 分钟前
Java 面向对象进阶之多态:从概念到实践的深度解析
java·开发语言·数据结构
鸽子炖汤5 分钟前
Java中==和equals的区别
java·开发语言·jvm
有个傻瓜9 分钟前
PHP语言核心技术全景解析
开发语言·kubernetes·php
菥菥爱嘻嘻32 分钟前
JS手写代码篇---手写ajax
开发语言·javascript·ajax
江梦寻38 分钟前
MacOS下Homebrew国内镜像加速指南(2025最新国内镜像加速)
开发语言·后端·python·macos·架构·策略模式
霖檬ing41 分钟前
Python——MySQL远程控制
开发语言·python·mysql
qq_429879672 小时前
省略号和可变参数模板
开发语言·c++·算法
优秀的颜3 小时前
计算机基础知识(第五篇)
java·开发语言·分布式
CodeWithMe3 小时前
【C/C++】std::vector成员函数清单
开发语言·c++
uyeonashi3 小时前
【QT控件】输入类控件详解
开发语言·c++·qt