Last active
February 28, 2025 11:29
-
-
Save PrintNow/17b6cdeadff98123f5a967f43a0a1397 to your computer and use it in GitHub Desktop.
使用 Go 读取 json5 文件
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"github.com/titanous/json5" | |
"os" | |
"strings" | |
) | |
//TIP <p>To run your code, right-click the code and select <b>Run</b>.</p> <p>Alternatively, click | |
// the <icon src="AllIcons.Actions.Execute"/> icon in the gutter and select the <b>Run</b> menu item from here.</p> | |
func main() { | |
// 读取 1.json5 文件 | |
data, err := os.ReadFile("1.json5") | |
if err != nil { | |
fmt.Printf("无法读取文件: %v\n", err) | |
return | |
} | |
// 删除 data 中的 \n 和转义 \ | |
cleanedData := string(data) | |
cleanedData = strings.ReplaceAll(cleanedData, "\\r\\n", "") | |
cleanedData = strings.ReplaceAll(cleanedData, "\\t", "") | |
cleanedData = strings.ReplaceAll(cleanedData, "\\n", "") | |
cleanedData = strings.ReplaceAll(cleanedData, "\\", "") | |
//fmt.Printf(cleanedData) | |
//return | |
// 更新解析时使用 cleanedData | |
data = []byte(cleanedData) | |
// 定义一个结构用于解析 JSON5 数据 | |
var result interface{} | |
// 使用 json5.Unmarshal 解析 | |
err = json5.Unmarshal(data, &result) | |
if err != nil { | |
fmt.Printf("解析 JSON5 数据出错: %v\n", err) | |
return | |
} | |
// 打印解析后的数据 | |
//fmt.Printf("解析结果: %+v\n", result) | |
// 打印解析 JSON5 的结构体 | |
if resultMap, ok := result.(map[string]interface{}); ok { | |
fmt.Printf("解析后的数据类型: %+v\n", resultMap["current"]) | |
} else { | |
fmt.Println("无法访问解析后的数据结构中的 'current' 字段") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment