导语:有一段json 如下 ,想根据传入的username的值匹配到对应的id。 对应功能是传入username,找到对应的id,删除对应的用户。
思路是 循环遍历这个数组,然后判断 看看username是否等于输入的username,如果等于输出对应索引的id。
直接上代码
package api
import (
"encoding/json"
"fmt"
"github.com/astaxie/beego"
)
type TestController struct {
BaseController
}
type Person struct {
Id int
// Name string
Username string
}
func (c *TestController) Get() {
var jsonBlob = []byte(`[
{"id":12,"name":"阿斯顿2","username":"asidun2"},
{"id":11,"name":"阿斯顿","username":"asidun"},
{"id":10,"name":"阿狗","username":"agou"},
{"id":9,"name":"阿猫","username":"amao"},
{"id":8,"name":"GitLab Alert Bot","username":"alert-bot"},
{"id":1,"name":"Administrator","username":"root"}
]`)
var person []Person
err := json.Unmarshal(jsonBlob, &person)
if err != nil {
fmt.Println("error:", err)
}
beego.Info("jq")
fmt.Printf("%+v", person)
fmt.Printf("out type:%T\n", person)
beego.Info("jq")
// beego.Info("jq")
// beego.Info(jq)
for _, v := range person {
// beego.Info(v)
beego.Info(v.Id, v.Username)
if v.Username != "asidun" {
beego.Info("用户名不匹配", v.Username)
} else {
beego.Info("用户名匹配成功", v.Username)
}
fmt.Printf("out type:%T\n", v)
}
c.Ctx.WriteString("content string")
}
直接请求http://localhost:8080/api/test
参考
https://blog.csdn.net/hp_cpp/article/details/101058472