doufei2194 2019-04-16 11:51
浏览 58
已采纳

如何检查KEY在json.RawMessage中是否存在?

I have a:

type User struct {
    UID                     int          `json:"id"`
    FirstName               string       `json:"first_name"`
    LastName                string       `json:"last_name"`
    Sex                     int          `json:"sex"`
    Nickname                string       `json:"nickname"`
    ScreenName              string       `json:"screen_name"`
    BDate                   string       `json:"bdate"`

}

code:

var userList []*User
json.Unmarshal(resp.Response, &userList)

server response may be:

[{"id":1,"first_name":"name","last_name":"last","sex":2,"nickname":"","screen_name":"screen","bdate":"1.1.1"}]

or

[{"id":1,"first_name":"name","sex":2,"nickname":"","screen_name":"screen"}]

my problem when calling a nonexistent KEY error runtime "userList[0].LastName":

error: index out of range

in the first case, the server returned:

"last_name":"last" and "bdate":"1.1.1"

in the second no

When there is no user, the server returns.

[{"error_code": 0, "error_msg": "Invalid user id"}]

answer:

    if len(userList) > 0 {
            c.String(http.StatusOK, "People name: %s", userList[0].FirstName)
        } else {
            c.String(http.StatusOK, "No People: %s", login)
        }

Thank Magestro

  • 写回答

1条回答 默认 最新

  • doumixiang2227 2019-04-16 12:09
    关注

    error: index out of range means that userList have no value with index [0], not about empty LastName

    In your example all works fine: https://play.golang.org/p/WHIqgB52w_I

    A u sure that server returns valid string and that this string exists in the resp.Response?

    Try print resp.Response and look for error in other place

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100