假设我有这样的json响应,正如您所看到的,有时电子邮件存在,有时不存在。现在我需要检查电子邮件密钥是否存在,并相应地漂亮地打印json响应。我该怎么做?
[
{"name" : "name1", "mobile": "123", "email": "email1@example.com", "carrier": "carrier1", "city", "city1"},
{"name" : "name2", "mobile": "1234", "carrier": "carrier2", "city", "city2"}
...
]
这里我需要检查p。电子邮件是否存在,如果存在,分配电子邮件值,如果不分配空字符串
for i, p := range jsonbody.Data {
a := p.Name
b := p.Phone[i].Mobile
c := p.INTaddress[i].Email // here i need to check
d := p.Phone[i].Carrier
e := p.Address[i].City
..........
}
我试着寻找,但没有找到任何关于戈兰的答案。
这里我需要检查p。电子邮件是否存在,如果存在,如果不分配空字符串,则分配电子邮件值
请注意,当您将字段定义为Email string
,并且传入的JSON不提供任何"email"
条目时,Email
字段将保持为空字符串,因此您可以直接使用它。不需要额外的检查。
如果您想允许null
,请使用Email *string
,并简单地使用if
条件来检查nil
,如072的回答所建议的。
当您需要区分undefined/null/empty时,请使用以下答案中建议的自定义解组器:
type String struct {
IsDefined bool
Value string
}
// This method will be automatically invoked by json.Unmarshal
// but only for values that were provided in the json, regardless
// of whether they were null or not.
func (s *String) UnmarshalJSON(d []byte) error {
s.IsDefined = true
if string(d) != "null" {
return json.Unmarshal(d, &s.Value)
}
return nil
}
https://go.dev/play/p/gs9G4v32HWL
然后,对于需要检查是否提供的字段,可以使用自定义String
而不是内置string
。要进行检查,您显然需要在解组发生后检查IsDefined
字段。
您可以使用指针,然后根据nil
:进行检查
package main
import (
"encoding/json"
"fmt"
)
var input = []byte(`
[
{"name" : "name1", "mobile": "123", "email": "email1@example.com", "carrier": "carrier1", "city": "city1"},
{"name" : "name2", "mobile": "1234", "carrier": "carrier2", "city": "city2"}
]
`)
type contact struct {
Name string
Email *string
}
func main() {
var contacts []contact
json.Unmarshal(input, &contacts)
// [{Name:name1 Email:0xc00004a340} {Name:name2 Email:<nil>}]
fmt.Printf("%+vn", contacts)
}