前提・実現したいこと
APIへリクエストして返ってきたJSONデータから1000件ほどを取得し、
必要な値のみJSONファイルとして保存したい。
発生している問題・エラーメッセージ
データの書き込みはできるが、VS CodeでEnd of file expectedとエラーがでる
該当のソースコード
Go
package main import ( "encoding/json" "fmt" "io" "log" "net/http" "os" "strconv" "time" ) type Api_info struct { api_ip string a_id string hits string output string } type Save_info struct { Title string `json:"title"` Aurl string `json:"a_url"` } func main() { api := Api_info{ api_ip: "exapmleexapmleexapmle", a_id: "exapmleexapmleexapmle", hits: "30", output: "json", } offset_count := 1 save_max_count := 1 num, _ := strconv.Atoi(api.hits) os.Create("test_4.json") for { url := "https://api.exapmleexapmleexapmle.com" request, err := http.NewRequest("GET", url, nil) if err != nil { log.Fatal(err) } params := request.URL.Query() params.Add("api_id", api.api_ip) params.Add("a_id", api.a_id) params.Add("hits", api.hits) params.Add("output", api.output) request.URL.RawQuery = params.Encode() fmt.Println(request.URL.String()) timeout := time.Duration(5 * time.Second) client := &http.Client{ Timeout: timeout, } response, err := client.Do(request) if err != nil { log.Fatal(err) break } defer response.Body.Close() body, err := io.ReadAll(response.Body) if err != nil { log.Fatal(err) } var jsonOBJ interface{} errr := json.Unmarshal(body, &jsonOBJ) if errr != nil { break } bb := jsonOBJ.(map[string]interface{})["result"] cc := bb.(map[string]interface{})["items"] c := cc.([]interface{}) for _, ii := range c { m := ii.(map[string]interface{}) Title := m["title"].(string) a_url := m["a_URL"].(string) file_json := Save_info{ Title, a_url, } jj, _ := json.MarshalIndent(file_json, "", " ") f, _ := os.OpenFile("test_4.json", os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.ModePerm) f.Write(jj) defer f.Close() } offset_count = num + offset_count } }
自分で調べたことや試したこと
osパッケージを利用したファイルへの追記方法や
json.Marshal , json.MarshalIndentなどの使い方を調べて書きました。
JSON単一情報を書き込む情報はあったので、
それを元にループ処理させるようにしましたが、
エラーが解消しません。
使っているツールのバージョンなど補足情報
go1.18.3 linux/amd64
VS Code 1.68.1
Ubuntu 22.04
お知恵を拝借できれば幸いです。
よろしくお願いいたします。
まだ回答がついていません
会員登録して回答してみよう