英文:
In Go-Lang how can i take JSON file and quote to css
问题
{
"data": "{\"address\": null, \"number\": \"-DI1\", \"_type\": \"\", \"model\": \"CI STO\", \"number\": \"603sjhhd2\",
}
英文:
I have sumfile.json that needs to be quoted into specific format.
{
"address": "312312321321",
"number": "d56"
"type": "chocolate",
"model": "dcdas55A",
"partnumber": "adasdasA",
...
and i have to make it look like this:
"data": "{\"address\": null, \"number\": \"-DI1\", \"_type\": \"\", \"model\": \"CI STO\", \"number\": \"603sjhhd2\",
答案1
得分: 2
只需将文件读取为字节切片,将字节转换为字符串,然后将字符串编组为JSON。
f, err := os.Open("sumfile.json")
if err != nil {
panic(err)
}
defer f.Close()
raw, err := io.ReadAll(f)
if err != nil {
panic(err)
}
out, err := json.Marshal(map[string]string{"data": string(raw)})
if err != nil {
panic(err)
}
fmt.Println(string(out))
https://go.dev/play/p/0lCwHLC8Tno
英文:
Just read the file into a byte slice, convert the bytes into a string, and then marshal the string as JSON.
f, err := os.Open("sumfile.json")
if err != nil {
panic(err)
}
defer f.Close()
raw, err := io.ReadAll(f)
if err != nil {
panic(err)
}
out, err := json.Marshal(map[string]string{"data": string(raw)})
if err != nil {
panic(err)
}
fmt.Println(string(out))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论