Salvador Dali
Salvador Dali

Reputation: 222929

Is it safe to assume that json.Marshall on a particular struct can not possibly fail?

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.

Upvotes: 1

Views: 769

Answers (1)

Art
Art

Reputation: 20402

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.

Upvotes: 7

Related Questions