いつもお世話になります。json形式のデータをブラウザで確認できるような形式で作成する方法を教えてください。例えば、http://localhost:8080/jsonでアクセスするとid:100のように表示されるようにしたいです。os.Createの際、urlをどのように指定すればよろしいのでしょうか。ご教授をお願いします。
package main import ( "encoding/json" "fmt" "io" "os" ) type Post struct { Id int `json:"id"` Content string `json:"content"` Author Author `json:"author"` Comments []Comment `json:"comments"` } type Author struct { Id int `json:"id"` Name string `json:"name"` } type Comment struct { Id int `json:"id"` Content string `json:"content"` Author string `json:"author"` } func main() { post := Post{ Id: 1, Content: "Hello World!", Author: Author{ Id: 2, Name: "Sau Sheong", }, Comments: []Comment{ Comment{ Id: 3, Content: "Have a great day!", Author: "Adam", }, Comment{ Id: 4, Content: "How are you today?", Author: "Betty", }, }, } jsonFile, err := os.Create("post.json") if err != nil { fmt.Println("Error creating JSON file:", err) return } jsonWriter := io.Writer(jsonFile) encoder := json.NewEncoder(jsonWriter) err = encoder.Encode(&post) if err != nil { fmt.Println("Error encoding JSON to file:", err) return } }
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。