I’m ended using custom json unmarshal function like this (in golang)
package main
import (
"encoding/json"
"fmt"
)
type School struct {
Name string `json:"name"`
Adress string `json:"address"`
}
type Student struct {
Name string `json:"name"`
School School `json:"school"`
}
func (s *Student) UnmarshalJSON(data []byte) error {
type TempStudent Student
temp := &struct {
*TempStudent
Schools []School `json:"study_at"`
}{TempStudent: (*TempStudent)(s)}
if err := json.Unmarshal(data, &temp); err != nil {
return err
}
if len(temp.Schools) == 1 {
s.School = temp.Schools[0]
}
return nil
}
func main() {
data := `{"name": "Crazy Student", "study_at": [{"name": "XYZ highschool", "address": "a school adresss"}]}`
var s Student
err := json.Unmarshal([]byte(data), &s)
if err != nil {
fmt.Println(err.Error())
}
fmt.Println(s.School.Name) //no more s.School[0].Name
}
but I still wishing built-in tag/filter in dgraph to return single object instead array for special case, maybe something like this:
{
query(func: eq(studentID, "001")) {
name
study_at @singleObject { # tag/filter to tell dgraph to return single object, instead array of object
name
address
}
}