go解析复杂json数组字符串:结合使用json和simple-json库
生活随笔
收集整理的這篇文章主要介紹了
go解析复杂json数组字符串:结合使用json和simple-json库
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
原始json數組字符串
[{"addition_links": {"build_history": {"absolute": false,"href": "/api/v2.0/projects/test/repositories/zhangxueliang%252Fmyapp/artifacts/sha256:5f4afc8302ade316fc47c99ee1d41f8ba94dbe7e3e7747dd87215a15429b9102/additions/build_history"}},"digest": "sha256:5f4afc8302ade316fc47c99ee1d41f8ba94dbe7e3e7747dd87215a15429b9102","extra_attrs": {"architecture": "amd64","author": null,"created": "2018-02-25T06:04:41.923389438Z","os": "linux"},"id": 176,"labels": null,"manifest_media_type": "application/vnd.docker.distribution.manifest.v2+json","media_type": "application/vnd.docker.container.image.v1+json","project_id": 7,"pull_time": "2021-12-17T01:59:08.570Z","push_time": "2021-01-06T01:58:10.546Z","references": null,"repository_id": 110,"size": 6755615,"tags": [{"artifact_id": 176,"id": 199,"immutable": false,"name": "v2","pull_time": "2021-12-17T01:59:08.570Z","push_time": "2021-01-06T01:58:10.568Z","repository_id": 110,"signed": false}],"type": "IMAGE"},{"addition_links": {"build_history": {"absolute": false,"href": "/api/v2.0/projects/test/repositories/zhangxueliang%252Fmyapp/artifacts/sha256:9eeca44ba2d410e54fccc54cbe9c021802aa8b9836a0bcf3d3229354e4c8870e/additions/build_history"}},"digest": "sha256:9eeca44ba2d410e54fccc54cbe9c021802aa8b9836a0bcf3d3229354e4c8870e","extra_attrs": {"architecture": "amd64","author": "MageEdu <mage@magedu.com>","created": "2018-03-02T03:39:41.482586301Z","os": "linux"},"id": 175,"labels": null,"manifest_media_type": "application/vnd.docker.distribution.manifest.v2+json","media_type": "application/vnd.docker.container.image.v1+json","project_id": 7,"pull_time": "2021-12-17T01:59:08.502Z","push_time": "2021-01-06T01:58:09.419Z","references": null,"repository_id": 110,"size": 6757253,"tags": [{"artifact_id": 175,"id": 198,"immutable": false,"name": "v1","pull_time": "2021-12-17T01:59:08.502Z","push_time": "2021-01-06T01:58:09.437Z","repository_id": 110,"signed": false}],"type": "IMAGE"} ]go代碼
package mainimport ("encoding/json""fmt""io/ioutil""net/http""time"simplejson "github.com/bitly/go-simplejson" )func main() {// 使用%252F轉義"/"url := "http://192.168.111.xxx:8603/api/v2.0/projects/test/repositories/zhangxueliang%252Fmyapp/artifacts"resp, err := http.Get(url)if err != nil {fmt.Println("報錯了")return}body, _ := ioutil.ReadAll(resp.Body)var rr []map[string]interface{}json.Unmarshal(body, &rr)for _, v := range rr {b, _ := json.Marshal(v)sj, err := simplejson.NewJson(b)if err != nil {panic(err)}tags, err := sj.Get("tags").Array()fmt.Println(tags)} }結果
解析出name字段
// fmt.Println(tags)for _, value := range tags {tagname, _ := value.(map[string]interface{})fmt.Println(tagname["name"])}
如果不進行斷言判斷,就會報錯:
可參考鏈接:
https://studygolang.com/articles/345
總結
以上是生活随笔為你收集整理的go解析复杂json数组字符串:结合使用json和simple-json库的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: go flag包获取命令行参数使用示例
- 下一篇: linux 用journalctl --