如何在解析json碰到缺失的字段时,避免 index out of range

错误:
panic: runtime error: index out of range [1] with length 1

原因:
json字串中,第三个对象的ipv4只有一个,导致在for-range循环里,调用machine.Data[i].Ipv4[1]时,下标溢出代码如下:
 

package main

import (
    "encoding/json"
    "fmt"
)

type JsonGet struct {
    Data []struct {
        ID   int      `json:"id"`
        Ipv4 []string `json:"ipv4"`
    } `json:"data"`
}

func main() {
    content := `
{
  "data": [
    {
      "id": 25590225,
      "ipv4": [
        "182.162.117.33",
        "192.168.136.56"
      ]
    },
    {
      "id": 25590642,
      "ipv4": [
        "113.129.70.169",
        "192.168.130.203"
      ]
    },
    {
      "id": 25591518,
      "ipv4": [
        "149.112.121.136"
      ]
    },
    {
      "id": 25592314,
      "ipv4": [
        "132.134.66.5",
        "192.168.133.19"
      ]
    }
  ]
}
    `
    var machine JsonGet
    err := json.Unmarshal([]byte(content), &machine)
    if err != nil {
        fmt.Println(err.Error())
    }
    for i := range machine.Data {
        fmt.Printf("%v\t\t%v\t\t%v\n", i, machine.Data[i].Ipv4[1], machine.Data[i].Ipv4[0])
    }
}


修正:

    for i := range machine.Data {
        if strings.Contains(machine.Data[i].Label, "bee") || strings.Contains(machine.Data[i].Label, "cmd") {
            fmt.Printf("%-3v\t%-10v\t", i, machine.Data[i].Label)
            for j := 0; j < len(machine.Data[i].Ipv4); j++ {
                fmt.Printf("%-15v\t\t", machine.Data[i].Ipv4[j])
            }
            fmt.Printf("\n")
        }
    }


原本是想把内网ip(machine.Data[i].Ipv4[1])放在前面,为了解决index out of range问题,就没要求这个顺序了
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值