jsongroovy

Parsing JSON5 in Groovy


I would like to parse a JSON5 object in Groovy, the reason why I want to use JSON5 is because I need to use the comment feature in groovy. So say for example, the JSON5 object would look like

{
  // comments 
"A":"123",
"B":"456"
}

This JSON5 object cannot be parsed by readJSON or JsonSlurper in Groovy.

I found there is a library in Python named JSON5 can do exactly what I needed, but the problem is my code is in Groovy.

So I am wondering if there is a library in Groovy can do this, or if there is any alternate decent way to handle it?


Solution

  • I don't see any implementation in java or groovy on official json5 site or github

    However, there is a parser type LAX in groovy that allows comments.

    import  groovy.json.*
    
    def json = '''
    {
      // comments 
      "A":"123",
      B: 456
    }
    '''
    
    def parser = new JsonSlurper()
    parser.type = JsonParserType.LAX
    def obj = parser.parseText(json)
    assert obj==[A:'123', B:456]
    

    https://docs.groovy-lang.org/latest/html/gapi/groovy/json/JsonParserType.html#LAX

    Beware - it's very unrestrictive. it allows keys and values without quotation.