Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a JSON with comments inside?

Tags:

json

go

In go the standard package encoding/json exposes json.Unmarshal function to parse JSON.

I have a JSON like this:

{
    ...
    "tyo": {
        "ping_only": true,
        "addresses": [
            //"155.133.245.25:27015-27050",
            //"155.133.245.26:27015-27050",
            //"155.133.245.27:27015-27050",
            "45.121.186.20:27015-27016",
            "45.121.186.21:27015-27016"
        ]
    },
    "vie": {
        "addresses": [
            "185.25.182.225:27015-27050",
            "185.25.182.226:27015-27050"
        ]
    },
    ...
}

When I use json.Unmarshal I got error:

Handler crashed with error invalid character '/' looking for beginning of value

Can someone tell me how to parse this?

like image 762
Viola Rulan Avatar asked Aug 03 '26 10:08

Viola Rulan


2 Answers

Strict JSON specification, don't allow comments.

But exist not-official superset of JSON that permits comments (and more other cool things), like JSON5 or HJSON (human-json).

You can try with these Go libraries:

  • JSON5: https://github.com/yosuke-furukawa/json5
  • HJSON: https://github.com/client9/xson/tree/master/hjson
like image 95
Dario Avatar answered Aug 05 '26 22:08

Dario


I wrote a simple json uncommenter in go that support line comment. use it before unmarshal.

    // f is a raw io.Reader
    newReader := jsonuncommenter.RemoveComment(f)

    jsonParser := json.NewDecoder(newReader)
    var s seeds
    jsonParser.Decode(&s)

https://github.com/wuxiangzhou2010/jsonuncommenter

like image 30
cathy Chou Avatar answered Aug 05 '26 22:08

cathy Chou