【发布时间】:2020-08-03 14:54:58
【问题描述】:
我正在尝试将 JSON 响应模板化到前端,我当前的结构是这样的:
type Response struct {
WhoisRecord struct {
CreatedDate time.Time `json:"createdDate"`
UpdatedDate time.Time `json:"updatedDate"`
ExpiresDate time.Time `json:"expiresDate"`
Registrant struct {
Name string `json:"name"`
Organization string `json:"organization"`
Street1 string `json:"street1"`
City string `json:"city"`
State string `json:"state"`
Country string `json:"country"`
CountryCode string `json:"countryCode"`
Email string `json:"email"`
Telephone string `json:"telephone"`
Fax string `json:"fax"`
} `json:"registrant"`
AdministrativeContact struct {
Name string `json:"name"`
Organization string `json:"organization"`
Street1 string `json:"street1"`
City string `json:"city"`
State string `json:"state"`
Country string `json:"country"`
CountryCode string `json:"countryCode"`
Email string `json:"email"`
Telephone string `json:"telephone"`
Fax string `json:"fax"`
} `json:"administrativeContact"`
TechnicalContact struct {
Name string `json:"name"`
Organization string `json:"organization"`
Street1 string `json:"street1"`
City string `json:"city"`
State string `json:"state"`
Country string `json:"country"`
CountryCode string `json:"countryCode"`
Email string `json:"email"`
Telephone string `json:"telephone"`
Fax string `json:"fax"`
} `json:"technicalContact"`
DomainName string `json:"domainName"`
NameServers struct {
HostNames []string `json:"hostNames"`
} `json:"nameServers"`
RegistrarName string `json:"registrarName"`
Ips []string `json:"ips"`
} `json:"WhoisRecord"`
}
然后我解组这个 json 响应,并将其传递到前端(我正在使用 GIN)
(响应被重新声明为res)
c.HTML(200,"homework.html", gin.H{
"whois": res,
})
但这是我遇到问题的地方,代码可以工作,但我不确定如何对其进行模板化,因为它是嵌套的。
例如,我想将注册人、管理人员和技术联系人详细信息(返回的所有字段)显示到单独的表格中。以及显示创建、更新和过期的日期。然后通过显示注册器、ips 和名称服务器(在本例中为 NameServers 下的 hostnames 字段)完成
我将如何在 homework.html 文件中提供此服务?我什么都试过了。通常我会做类似的事情:
显示 IP:
{{ range .Ips }}
<div>
<p>IP</p>
<h6>{{ . }}</h6>
</div>
{{end}}
显示寄存器数据:
<div>
<p>Name</p>
<h6>{{ .Name }}</h6>
<p>Email</p>
<h6>{{ .Email }}</h6>
//etc
</div>
显示注册器:
<div>
<p>Registrar</p>
<h6>{{ .RegistrarName }}</h6>
</div>
但是这些都不起作用(我如何在一个字段中显示注册人姓名,然后在另一个字段中显示技术名称?我显然把模板搞砸了,我对它的理解有点歪曲)。我已经阅读了我所能阅读的所有内容,我试图划分结构并作为单独的结构,等等。没有任何工作。有人能指出我正确的方向并举例吗?
谢谢!
【问题讨论】:
-
试试
{{range .whois.Ips}} -
@BurakSerdar 有效,但是我如何访问其他深层嵌套的 json?这也是通过另一个错误,但至少它有点工作。虽然我修复了另一个,但我仍然想知道如何访问深层嵌套结构并了解正在发生的事情
-
您正在访问结构字段,而不是 json。该结构被放置在一个名为“whois”的变量中,因此您可以从那里使用点符号:.whois.Registrant.Name 等
-
@BurakSerdar 你的回答救了我!您可以提交它以便我标记为解决方案吗?