【发布时间】:2022-02-03 06:33:00
【问题描述】:
我正在调用 API 并尝试解析正文响应以过滤掉数据。我创建了一个条件 for 循环来遍历每个对象并检查此字段:Relationships.CurrentConfigurationVersion.Data 是否为空。
这是我的第一次尝试:
func (s *Server) getEmptyWorkSpaces(w http.ResponseWriter, r *http.Request) {
// omitted API calls for brevity
// body holds the JSON response
body, err := ioutil.ReadAll(resp.Body)
// label my struct type as data
var data WorkspacesJSON
err = json.Unmarshal(body, data)
if err != nil {
panic(err)
}
var data2 []*WorkspacesJSON
for _, v := range data.Data {
if v.Relationships.CurrentConfigurationVersion.Data == " " {
data2 = append(data2, v)
}
}
}
条件语句中出现错误是因为我将结构类型与字符串进行比较。
无法将“”(无类型字符串常量)转换为struct{ID string“json:”id””;键入字符串 "json:"type""}
尝试 2 经过一番搜索后,我从我学到的信息中尝试了另一种尝试:
func (s *Server) getEmptyWorkSpaces(w http.ResponseWriter, r *http.Request) {
// omitted API calls for brevity
// body holds the JSON response
body, err := ioutil.ReadAll(resp.Body)
// label my struct type as data, this time attach []*
var data []*WorkspacesJSON
// added & in this new attempt
err = json.Unmarshal(body, &data)
if err != nil {
panic(err)
}
var data2 []*WorkspacesJSON
for _, v := range data.Data {
if v.Relationships.CurrentConfigurationVersion.Data == " " {
data2 = append(data2, v)
}
}
}
编译器抛出另一个错误,但这次针对 v.Relationships.CurrentConfigurationVersion.Data 说:
v.Relationships undefined (type *WorkspacesJSON has no field or methodRelationships)compilerMissingFieldOrMethod 我不确定为什么会出现此错误,因为在我的第一次尝试中这不是问题?显然我不明白这一点。
这是我的type struct:
它相当长,但唯一重要的字段是Data.Relationships.CurrentConfigurationVersion.Data
type WorkspacesJSON struct {
Data []struct {
ID string `json:"id"`
Type string `json:"type"`
Attributes struct {
AllowDestroyPlan bool `json:"allow-destroy-plan"`
AutoApply bool `json:"auto-apply"`
AutoDestroyAt interface{} `json:"auto-destroy-at"`
CreatedAt time.Time `json:"created-at"`
Environment string `json:"environment"`
Locked bool `json:"locked"`
Name string `json:"name"`
QueueAllRuns bool `json:"queue-all-runs"`
SpeculativeEnabled bool `json:"speculative-enabled"`
StructuredRunOutputEnabled bool `json:"structured-run-output-enabled"`
TerraformVersion string `json:"terraform-version"`
WorkingDirectory string `json:"working-directory"`
GlobalRemoteState bool `json:"global-remote-state"`
UpdatedAt time.Time `json:"updated-at"`
ResourceCount int `json:"resource-count"`
ApplyDurationAverage int `json:"apply-duration-average"`
PlanDurationAverage int `json:"plan-duration-average"`
PolicyCheckFailures int `json:"policy-check-failures"`
RunFailures int `json:"run-failures"`
WorkspaceKpisRunsCount int `json:"workspace-kpis-runs-count"`
LatestChangeAt time.Time `json:"latest-change-at"`
Operations bool `json:"operations"`
ExecutionMode string `json:"execution-mode"`
VcsRepo struct {
Branch string `json:"branch"`
IngressSubmodules bool `json:"ingress-submodules"`
Identifier string `json:"identifier"`
DisplayIdentifier string `json:"display-identifier"`
OauthTokenID string `json:"oauth-token-id"`
WebhookURL string `json:"webhook-url"`
RepositoryHTTPURL string `json:"repository-http-url"`
ServiceProvider string `json:"service-provider"`
} `json:"vcs-repo"`
VcsRepoIdentifier string `json:"vcs-repo-identifier"`
Permissions struct {
CanUpdate bool `json:"can-update"`
CanDestroy bool `json:"can-destroy"`
CanQueueDestroy bool `json:"can-queue-destroy"`
CanQueueRun bool `json:"can-queue-run"`
CanQueueApply bool `json:"can-queue-apply"`
CanReadStateVersions bool `json:"can-read-state-versions"`
CanCreateStateVersions bool `json:"can-create-state-versions"`
CanReadVariable bool `json:"can-read-variable"`
CanUpdateVariable bool `json:"can-update-variable"`
CanLock bool `json:"can-lock"`
CanUnlock bool `json:"can-unlock"`
CanForceUnlock bool `json:"can-force-unlock"`
CanReadSettings bool `json:"can-read-settings"`
CanManageTags bool `json:"can-manage-tags"`
} `json:"permissions"`
Actions struct {
IsDestroyable bool `json:"is-destroyable"`
} `json:"actions"`
Description interface{} `json:"description"`
FileTriggersEnabled bool `json:"file-triggers-enabled"`
TriggerPrefixes []interface{} `json:"trigger-prefixes"`
Source string `json:"source"`
SourceName interface{} `json:"source-name"`
SourceURL interface{} `json:"source-url"`
TagNames []interface{} `json:"tag-names"`
} `json:"attributes"`
Relationships struct {
Organization struct {
Data struct {
ID string `json:"id"`
Type string `json:"type"`
} `json:"data"`
} `json:"organization"`
CurrentRun struct {
Data struct {
ID string `json:"id"`
Type string `json:"type"`
} `json:"data"`
Links struct {
Related string `json:"related"`
} `json:"links"`
} `json:"current-run"`
LatestRun struct {
Data struct {
ID string `json:"id"`
Type string `json:"type"`
} `json:"data"`
Links struct {
Related string `json:"related"`
} `json:"links"`
} `json:"latest-run"`
Outputs struct {
Data []interface{} `json:"data"`
} `json:"outputs"`
RemoteStateConsumers struct {
Links struct {
Related string `json:"related"`
} `json:"links"`
} `json:"remote-state-consumers"`
CurrentStateVersion struct {
Data struct {
ID string `json:"id"`
Type string `json:"type"`
} `json:"data"`
Links struct {
Related string `json:"related"`
} `json:"links"`
} `json:"current-state-version"`
CurrentConfigurationVersion struct {
Data struct {
ID string `json:"id"`
Type string `json:"type"`
} `json:"data"`
Links struct {
Related string `json:"related"`
} `json:"links"`
} `json:"current-configuration-version"`
AgentPool struct {
Data interface{} `json:"data"`
} `json:"agent-pool"`
Readme struct {
Data struct {
ID string `json:"id"`
Type string `json:"type"`
} `json:"data"`
} `json:"readme"`
} `json:"relationships"`
Links struct {
Self string `json:"self"`
} `json:"links"`
} `json:"data"`
Links struct {
Self string `json:"self"`
First string `json:"first"`
Prev interface{} `json:"prev"`
Next string `json:"next"`
Last string `json:"last"`
} `json:"links"`
Meta struct {
StatusCounts struct {
Pending int `json:"pending"`
PlanQueued int `json:"plan-queued"`
Planning int `json:"planning"`
Planned int `json:"planned"`
Confirmed int `json:"confirmed"`
ApplyQueued int `json:"apply-queued"`
Applying int `json:"applying"`
Applied int `json:"applied"`
Discarded int `json:"discarded"`
Errored int `json:"errored"`
Canceled int `json:"canceled"`
CostEstimating int `json:"cost-estimating"`
CostEstimated int `json:"cost-estimated"`
PolicyChecking int `json:"policy-checking"`
PolicyOverride int `json:"policy-override"`
PolicyChecked int `json:"policy-checked"`
PolicySoftFailed int `json:"policy-soft-failed"`
PlannedAndFinished int `json:"planned-and-finished"`
PostPlanRunning int `json:"post-plan-running"`
PostPlanCompleted int `json:"post-plan-completed"`
PreApplyRunning int `json:"pre-apply-running"`
PreApplyCompleted int `json:"pre-apply-completed"`
Fetching int `json:"fetching"`
None int `json:"none"`
Total int `json:"total"`
} `json:"status-counts"`
Pagination struct {
CurrentPage int `json:"current-page"`
PageSize int `json:"page-size"`
PrevPage interface{} `json:"prev-page"`
NextPage int `json:"next-page"`
TotalPages int `json:"total-pages"`
TotalCount int `json:"total-count"`
} `json:"pagination"`
} `json:"meta"`
}
我陷入了上述两个相同错误的永恒循环,并试图创建 hacky 函数来完成工作,但没有运气。
我对 Go 很陌生,我有使用 Python 的经验,并且在 Py 中使用 JSON 对我来说要容易得多,但我想用 Go 来尝试一下。提前感谢您的指导。
如何使用条件过滤我的 JSON body 以检查字段是否为空?
编辑:
在我的第二次尝试中,我如何能够选择我正在寻找的字段Relationships.CurrentConfigurationVersion.Data?一旦我弄清楚了,我想我会没事的。目前它的说法是WorkspaceJSON 没有Relationships 的方法字段。这不是我第一次尝试的情况。
【问题讨论】:
-
@Zombo,我不想输入任何 JSON,我只是想过滤 JSON 正文响应。我有条件地比较,因为我试图过滤掉这个字段的 JSON 对象。Relationships.CurrentConfigurationVersion.Data 为空,“”。
-
@andres:您的类型与附加工作不匹配,
data2被定义为[]*WorkspacesJSON,但是当您过滤v时,它的类型为Data -
@Zombo 预期的结果是
body中所有通过条件的 JSON 对象,这意味着Relationships.CurrentConfigurationVersion.Data为空。我会举一个例子,但都是敏感数据。 -
@Inian,这将是编译器尚未发现的另一个错误?我该如何解决它。
-
如果你想检查
...Data字段是否为空,你必须与相同类型的空值进行比较,即struct {ID string; Type string },所以要检查Data是否为空,你有做go.dev/play/p/daKmsxjjiOV