In Go-Lang how can i take JSON file and quote to css

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

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))

https://go.dev/play/p/0lCwHLC8Tno

huangapple
  • 本文由 发表于 2022年8月31日 01:35:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/73546446.html
匿名

发表评论

匿名网友

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

确定