假設我有一個這樣的 json 回應,正如您所看到的,有時電子郵件有時不存在。現在我需要檢查電子郵件密鑰是否存在,并相應地列印 json 回應。我怎樣才能做到這一點?
[
{"name" : "name1", "mobile": "123", "email": "[email protected]", "carrier": "carrier1", "city", "city1"},
{"name" : "name2", "mobile": "1234", "carrier": "carrier2", "city", "city2"}
...
]
在這里我需要檢查 p.Email 是否存在,如果存在則分配電子郵件值,如果不分配空字串
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
..........
}
我嘗試搜索但沒有找到 golang 的任何答案。
uj5u.com熱心網友回復:
在這里我需要檢查 p.Email 是否存在,如果存在則分配電子郵件值,如果不分配空字串
請注意,當您將欄位定義為Email string并且傳入的 JSON 不提供任何 "email"條目時,該Email欄位將保持為空字串,因此您可以按原樣使用它。無需額外檢查。
如果您想允許null使用Email *string,只需按照 072 的答案建議使用if條件進行檢查。nil
當您需要區分 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檢查該欄位。
uj5u.com熱心網友回復:
您可以使用指標,然后檢查nil:
package main
import (
"encoding/json"
"fmt"
)
var input = []byte(`
[
{"name" : "name1", "mobile": "123", "email": "[email protected]", "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("% v\n", contacts)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/513513.html
標籤:json去解析
上一篇:將資料從json提取到CSV
