从[]byte中删除C风格的注释

huangapple go评论73阅读模式
英文:

Strip out C-style comments from a []byte

问题

我正在尝试为一种特定类型的配置文件编写一个包装器,该文件是JSON编码的。不幸的是,这个文件包含C风格的注释(///* */),这些注释会导致json.Unmarshal出错。有没有办法强制Unmarshal忽略这些注释,或者轻松地将它们删除?

我现在正在研究regexp,但我希望有一个优雅的解决方案,作为Go的初学者,我可能无法在几分钟内想出来。

英文:

all. I'm trying to write a wrapper for a particular type of config file, which is JSON encoded. Unfortunately, this file contains C-style comments, (// and /* */,) and these cause errors in json.Unmarshal. Is there a way force Unmarshal to ignore these comments, or otherwise remove them easily?

I'm looking into regexp now, but I'm hoping there's an elegant solution that I, as a beginner in Go, might not be able to come up with in the course of a few minutes.

答案1

得分: 8

You'll have to strip out the comments, as the JSON specification does not allow comments. A regular expression can do the job.

package main

import (
	"fmt"
	"regexp"
)

var bytes = []byte(`// this is a line comment
this is outside the comments
/* this
   is
   a
   multi-line
   comment */`)

func main() {
	re := regexp.MustCompile(`(?s)//.*?\n|/\*.*?\*/`)
	newBytes := re.ReplaceAll(bytes, nil)
	fmt.Println(string(newBytes))
}
英文:

You'll have to strip out the comments, as the JSON specification does not allow comments. A regular expression can do the job.

package main

import (
	"fmt"
	"regexp"
)

var bytes = []byte(`// this is a line comment
this is outside the comments
/* this
   is
   a
   multi-line
   comment */`)

func main() {
	re := regexp.MustCompile("(?s)//.*?\n|/\\*.*?\\*/")
	newBytes := re.ReplaceAll(bytes, nil)
	fmt.Println(string(newBytes))
}

答案2

得分: -1

你肯定需要写一些东西,因为JSON不允许有注释,所以我会很惊讶如果go json包能够忽略不属于规范的注释。

英文:

You'll most certainly need to write something up as JSON doesn't allow for comments, so likewise I'd be surprised if the go json pkg facilitated ignoring comments that aren't part of the spec.

huangapple
  • 本文由 发表于 2012年10月2日 07:14:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/12682405.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定