【发布时间】:2019-12-21 13:34:58
【问题描述】:
(注意,这个问题不需要 Dgraph;它只是我遇到问题时使用的工具)
假设你有一些结构
type AccountSettings struct {
Uid string `json:"uid"`
DType string `json:"dgraph.type"`
Name string `json:"name"`
Username string `json:"username"`
}
type Settings struct {
Uid string `json:"uid"`
DType string `json:"dgraph.type"`
Account AccountSettings `json:"account"`
}
type Tag struct {
Uid string `json:"uid"`
DType string `json:"dgraph.type"`
Label Label `json:"label"`
}
type User struct {
Uid string `json:"uid"`
DType string `json:"dgraph.type"`
Settings Settings `json:"settings"`
Tags []Tag `json:"tags"`
}
然后您创建一个用户并将其添加到您的 Dgraph 数据库中
user = User{
DType: "User",
Settings: Settings{
DType: "Settings",
Account: SettingsAccount{
DType: "SettingsAccount",
Name: "Billy Bob"
Username: "billyboy123"
},
Tags: []Tag{{
DType: "Tag",
Label: "admin"
}, {
DType: "Tag",
Label: "user"
}}
},
}
然后你查询你的 Dgraph 数据库(假设你有用户节点的 uid)
{
user(func: uid("0x1234")) {
uid
settings {
account {
name
username
}
}
tags {
label
}
}
}
响应将返回为
{
"data": {
"user": [
{
"uid": "0x1234"
"settings": [
{
"account": [
{
"name": "Billy Bob",
"username": "billyboy123"
}
]
}
]
"tags": [
{
label: "admin"
},
{
label: "user"
},
]
}
]
}
}
所以问题是 Dgraph 的 JSON 响应将返回结构类型的字段作为数组(大概是因为可能有多个节点指向单个其他节点),但是由于它是一个数组,所以不能立即编组它带有User 结构(因为User.Settings 的类型是Settings,而不是[]Settings)。
为了使用 User 结构(或任何其他类型的结构)编组 Dgraph JSON 响应,您会做什么?
请务必注意,JSON 响应中的 settings 数组应该只是该数组中的第一个元素,但 tags 数组应该仍然是一个数组,因为这是在 User 结构中指定的。
【问题讨论】: