duanjing3656 2017-10-30 06:16
浏览 46
已采纳

是否可以安全地假设特定结构上的json.Marshall不可能失败?

I have read this question which asks whether json.Marshal can fail on any input and based on the answers it looks like for my situation it can't fail. My situation is the following:

I have a specific struct (no nesting, no arrays, just strings, ints of various types, bools). I need to marshal it into a json. Can it ever fail?

In more specific example:

type some struct {
    F1 string `json:"f1"`
    F2 uint32 `json:"f2"`
    F3 int64  `json:"f3"`
    F4 bool   `json:"f4"`
}

func doSomething(s some) (string, error) {
    data, err := json.Marshal(s)
    if err != nil {
        return "", err
    }
    return string(data), nil
}

Can doSomething ever fail? If yes, please provide an input, otherwise explain why not. Based on my current knowledge it can't.

  • 写回答

1条回答 默认 最新

  • dongwo2772 2017-10-30 08:01
    关注

    There are three potential error sources I can see here:

    1. strings and various UTF8 stuff

    2. int64. Numbers in JSON are usually treated as float64, so a pedantic implementation could return an error for numbers with absolute values bigger than 2^53 because they could be dangerous.

    3. reflect.

    1 and 2 don't currently happen (the functions in encoding/json don't return errors or panic). I haven't dug into the code of reflect to verify 3, but this is one of those trivially testable cases. Either it fails on the first attempt or always works.

    On the other hand. In the past the json encoder would return errors if strings contained invalid UTF8 characters. It no longer does that, but this points to an important principle - things change. Just because a certain error isn't returned today doesn't mean that there won't be errors in the future. The function is defined to return errors. This means that it is perfectly valid for the standard library developers to start returning new errors in the future for things that might not be errors today. So the answer is - yes, it can fail. Maybe not today but code that depends on a particular version of a standard library is bad code.

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

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀