git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/jsonutil/comments.go (about)

     1  package jsonutil
     2  
     3  import (
     4  	"bufio"
     5  	"bytes"
     6  	"fmt"
     7  	"strings"
     8  )
     9  
    10  func StripComments(input []byte) (output []byte, err error) {
    11  	var jsonString string
    12  	// Strip comments
    13  	confScanner := bufio.NewScanner(bytes.NewReader(input))
    14  	for confScanner.Scan() {
    15  		line := confScanner.Text() // GET the line string
    16  		if !strings.HasPrefix(strings.TrimSpace(line), "//") {
    17  			jsonString += line + "\n"
    18  		}
    19  	}
    20  	if err = confScanner.Err(); err != nil {
    21  		err = fmt.Errorf("jsonutil.StripComments: scanning input: %w", err)
    22  		return
    23  	}
    24  
    25  	output = []byte(jsonString)
    26  
    27  	return
    28  }