Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

encoding/json: Marshal outputs invalid JSON when json.Number contains an invalid number #12793

dyatlov opened this issue Sep 30, 2015 · 4 comments


Copy link

dyatlov commented Sep 30, 2015

See this discussion:!topic/golang-nuts/EErMkG2NWIM

Playground example:

My service parses JSON data from multiple 3rd party websites and they all provide json differently.. some of them use numbers, some use strings.. after receiving json I do several manipulations with it and then pass it to other service.. but it in cases when site returns invalid number - my json becomes invalid too which shouldn't happen by design.. json.Number value in this case should contain 0, right?

Copy link

Please don't ignore error return values, especially in bug reports. That's not the problem here, but people may not believe the bug report as much if you throw away errors.

Better example:

package main

import (

type js struct {
    Test1 json.Number `json:"test1"`
    Test2 json.Number `json:"test2"`

func main() {
    res, err := json.Marshal(js{
        Test1: "100",
        Test2: "100%",
    fmt.Printf("%s, %v", res, err)


{"test1":100,"test2":100%}, <nil>

Copy link

dyatlov commented Sep 30, 2015

Thank you Brad,
I think it's hard to solve the problem without breaking backward compatibility.. for current apps solution could be to use interface{} instead of json.Number and then do conversion manually or reassign json.Number value to a new one right after Unmarshalling.

That type Number string makes things very difficult.

I can think of an option for json.Decoder which would accept callback to validate json.Number or an option which would provide a regex to validate it.
This would help with Unmarshalling.
As about your example - I think json.Number should be defined as a struct/interface and assigning to a Number would be possible only by creating a new struct. Automatic Number <-> String should never happen.

Copy link

Dup of #10281?

Copy link


@golang golang locked and limited conversation to collaborators Oct 4, 2016
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
None yet

No branches or pull requests

4 participants