Skip to content

Instantly share code, notes, and snippets.

@jroenf
Created July 1, 2024 07:27
Show Gist options
  • Save jroenf/99232e06a969f9c5335f86e512625a2d to your computer and use it in GitHub Desktop.
Save jroenf/99232e06a969f9c5335f86e512625a2d to your computer and use it in GitHub Desktop.
Go script to extract a list of ids and names in .csv format from a json file
package main
import (
"encoding/csv"
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"strconv"
)
type Data struct {
ID int `json:"id"`
Name string `json:"title"`
}
func main() {
urls := "https://someapi.com/api/accommodations/?organization=1539" // replace with your URL
resp, err := http.Get(urls)
if err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
fmt.Printf("Received non 200 response code, got: %d\n", resp.StatusCode)
return
}
var data []Data
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
fmt.Println(err)
return
}
parsedUrl, err := url.Parse(urls)
if err != nil {
fmt.Println(err)
return
}
values := parsedUrl.Query()
idStr := values.Get("organization") // replace "your_query_param" with the actual query parameter name
id, err := strconv.Atoi(idStr)
if err != nil {
fmt.Println(err)
return
}
file, err := os.Create(fmt.Sprintf("hotel_%d.csv", id))
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
writer := csv.NewWriter(file)
writer.Comma = '\t'
defer writer.Flush()
err = writer.Write([]string{"id", "title"})
if err != nil {
fmt.Println(err)
return
}
for _, d := range data {
if err := writer.Write([]string{strconv.Itoa(d.ID), d.Name}); err != nil {
fmt.Println(err)
return
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment