英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论