我需要遍歷 json 檔案中的所有答案選項:
{"questions": [
{"id": 1,
"question": "What is your marital status?",
"answer":[ {
"text": "Single",
"next_question": 2
},
{
"text": "Married",
"next_question": 3
}]
},
{"id":2,
"question": "Are you planning on getting married next year?",
"answer":[{
"text": "Yes",
"next_question": 3
},
{
"text": "No",
"next_question": 5
}]},
{"id":3,
"question": "How long have you been married?",
"answer": [{
"text": "Less than a year",
"next_question": 6
},
{
"text": "More than a year",
"next_question": 4
}]},
{"id":4,
"question":"Have you celebrated your one year anniversary?",
"answer": [{
"text": "Yes",
"next_question": 7
},
{
"text": "No",
"next_question": 8
}]}
]}
并寫下路徑和編號,例如:
{"paths": {"number": 3, "list": [
[{"What is your marital status?": "Single"},
{"Are you planning on getting married next year?": "Yes/No"}],
[{"What is your marital status?": "Married"},
{"How long have you been married?": "Less than a year"}],
[{"What is your marital status?": "Married"},
{"How long have you been married?": "More than a year"},
{"Have you celebrated your one year anniversary?": "Yes/No"}]
]}}
您可以根據需要更改 JSON 結構,但主要是顯示有關所有可能輪詢路徑 (paths.number) 的數量的資訊,以及通過一系列帶有答案的問題 (paths.list) 顯示所有可能路徑的資訊
因此,我將 JSON 決議為以下結構:
type (
Answer struct {
Text string `json:"text"`
NextQuestion int `json:"next_question"`
}
Question struct {
Id int `json:"id"`
Question string `json:"question"`
Answer []Answer `json:"answer"`
}
Input struct {
Questions []Question `json:"questions"`
}
)
并嘗試迭代:
func (input Input) Script(itterQuestion []Question, element Question) []Question {
itterQuestion = append(itterQuestion, element)
for i, item := range input.Questions {
if item.Id != itterQuestion[i].Id {
itterQuestion = append(itterQuestion, item)
} else {
return input.Script(itterQuestion, item)
}
}
return itterQuestion
}
但我不明白如何正確地為 json 撰寫遞回函式和輸出結構。
uj5u.com熱心網友回復:
由于您要創建多個路徑,因此必須有[][]Question. 此外,您必須附加遞回函式的結果,而不是只回傳。
這是作業示例:
func (input Input) Script (id int) (out [][]Question) {
for _, q := range input.Questions {
if q.Id == id {
added := false // avoid add last multiple times
for _, answer := range q.Answer {
paths := input.Script(answer.NextQuestion)
if len(paths) == 0 && !added {
// answer has no next question | question not found in input
out = append(out, []Question{q})
added = true
}
for _, path := range paths {
// prepend question to every path from recursive function
path = append([]Question{q}, path...)
out = append(out, path)
}
}
return out
}
}
return out
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/450160.html
下一篇:如何從地圖內的切片中洗掉元素?
