我正在尝试将一个简单的降价文件转换为 json,降价看起来像这样:
#TITLE 1
- Line 1
- Line 2
- Line 3
#TITLE 2
- Line 1
- Line 2
- Line 3
<!-- blank line -->
我不明白在func main() 中重构以下内容需要什么:
type Section struct {
Category string
Lines []string
}
file, _ := os.Open("./src/basicmarkdown/basicmarkdown.md")
defer file.Close()
rgxRoot, _ := regexp.Compile("^#[^#]")
rgxBehaviour, _ := regexp.Compile("^-[ ]?.*")
scanner := bufio.NewScanner(file)
ruleArr := []*Section{}
rule := &Section{}
for scanner.Scan() {
linetext := scanner.Text()
// If it's a blank line
if rgxRoot.MatchString(linetext) {
rule := &Section{}
rule.Category = linetext
}
if rgxBehaviour.MatchString(linetext) {
rule.Lines = append(rule.Lines, linetext)
}
if len(strings.TrimSpace(linetext)) == 0 {
ruleArr = append(ruleArr, rule)
}
}
jsonSection, _ := json.MarshalIndent(ruleArr, "", "\t")
fmt.Println(string(jsonSection))
上面的代码输出:
[
{
"Category": "",
"Lines": [
"- Line 1",
"- Line 2",
"- Line 3",
"- Line 1",
"- Line 2",
"- Line 3"
]
},
{
"Category": "",
"Lines": [
"- Line 1",
"- Line 2",
"- Line 3",
"- Line 1",
"- Line 2",
"- Line 3"
]
}
]
当我希望输出时:
[
{
"Category": "#TITLE 1",
"Lines": [
"- Line 1",
"- Line 2",
"- Line 3"
]
},
{
"Category": "#TITLE 2",
"Lines": [,
"- Line 1",
"- Line 2",
"- Line 3"
]
}
]
肯定有几件事是错的。请原谅这个问题的冗长,当你是一个菜鸟时,如果没有例子就很难解释。提前致谢。
呼啦一阵风
相关分类