英文:
Dynamic struct with result object in Go Language
问题
我想创建一个具有动态数据结构的结果对象 JSON,例如在 func1 中,结果如下所示:
{
"result": "this is result",
"content": {
"func1": "value",
"some_desc_func1": "value"
}
}
而 func2 的结果可能只是这样(只关注 content):
{
"result": "this is result",
"content": {
"func2": "value"
}
}
根据这个参考链接 https://stackoverflow.com/a/35657622/4476788,我想显示只有一个 result 键的结果 JSON。
像这样:
{
"result": "this is result",
"content": {
"key": "value"
}
}
而不是像这样:
[
{
"result_1": "answer 1"
},
{
"result_2": "answer 2"
}
]
我尝试更新答案的 playground,但出现错误:
type Brand struct {
Name string
}
var database map[string]interface{}
func init() {
database = make(map[string]interface{})
brands := make([]Brand, 1)
brands = Brand{"Gucci"}
database["brands"] = brands
}
你可以在这里运行它 https://play.golang.org/p/mKCwKEVI7E
它显示错误:
tmp/sandbox651609402/main.go:22: cannot use Brand literal (type Brand) as type []Brand in assignment
英文:
I want to create result object json with dynamic structure of data, ex
in func1 the result is like this
<!-- language: lang-html -->
{
'result': 'this is result',
'content': {
'func1' : 'value',
'some_desc_func1': 'value'
}
}
<!-- end snippet -->
and func2 maybe the result is just (focus on content) like this
<!-- language: lang-html -->
{
'result': 'this is result',
'content': {
'func2' : 'value'
}
}
<!-- end snippet -->
As this reference https://stackoverflow.com/a/35657622/4476788, i want to show result json with just one key of result.
Like this
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
{
'result': 'this is result',
'content': {
'key' : 'value'
}
}
<!-- end snippet -->
And not like this
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
[
{
'result_1' : 'answer 1'
},
{
'result_2' : 'answer 2'
}
]
<!-- end snippet -->
i try to update the play ground of the answer but it showing error
type Brand struct {
Name string
}
var database map[string]interface{}
func init() {
database = make(map[string]interface{})
brands := make([]Brand, 1)
brands = Brand{"Gucci"}
database["brands"] = brands
}
You can try run in here https://play.golang.org/p/mKCwKEVI7E
it showing error
tmp/sandbox651609402/main.go:22: cannot use Brand literal (type Brand) as type []Brand in assignment
答案1
得分: 1
第22行应该是:brands = []Brand{Brand{"Gucci"}}
英文:
Line 22 should be: brands = []Brand{Brand{"Gucci"}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论