json이 올바르게 형식화되지 않은 것 외에도 다음은 struct 및 json struct 태그를 사용하여 json을 만드는 방법의 예입니다.
적절한 JSON
[ {키 값, 키 값}, {키 값, 키 값} ]
당신이 가진 것은 은 {키 값, 키 값} {key : value, key value}
배열에서 하나의 객체가 아닌 두 개의 개별 객체입니다.
파일에서 이것을 읽고 데이터가 예제와 같이 반환되는 경우 개행을 분리하여 각 객체를 분리하고 개별적으로 비 정렬 화해야 할 수 있습니다.
그렇지 않은 경우 아래 예가 서버입니다.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"strconv"
)
type j struct {
Cl []string `json:"cl"`
Gr []string `json:"gr"`
Cr []string `json:"cr"`
}
func main() {
// create an instance of j as a slice
var data []j
// using a for loop for create dummy data fast
for i := 0; i < 5; i++ {
v := strconv.Itoa(i)
data = append(data, j{
Cl: []string{"foo " + v},
Gr: []string{"bar " + v},
Cr: []string{"foobar " + v},
})
}
// printing out json neatly to demonstrate
b, _ := json.MarshalIndent(data, "", " ")
fmt.Println(string(b))
// writing json to file
_ = ioutil.WriteFile("file.json", b, 0644)
// to append to a file
// create the file if it doesn't exists with O_CREATE, Set the file up for read write, add the append flag and set the permission
f, err := os.OpenFile("/var/log/debug-web.log", os.O_CREATE|os.O_RDWR|os.O_APPEND, 0660)
if err != nil {
log.Fatal(err)
}
// write to file, f.Write()
f.Write(b)
// if you are doing alot of I/O work you may not want to write out to file often instead load up a bytes.Buffer and write to file when you are done... assuming you don't run out of memory when loading to bytes.Buffer
}
유효하지 않은 JSON입니다. 항목 그룹이있는 경우 각 요소를 쉼표로 구분하여 배열에 필요할 수 있습니다. – Joe
내가 어떻게 보이는지 보여 줄 수 있습니까? 나는 웹상에서 보았지만 나는 혼란 스럽다. @Joe – HubbA
[{ "cl": "[v1]", ...}, { "cl": "[v2]", ...}] – Joe