在Golang中读取在线JSON并将值保存为CSV



我目前能够解码程序内JSON。

但是,我想解码在线JSON并将一些值保存为CSV文件中的值。

下面是我当前的代码:http://play.golang.org/p/tVz4cEaL-R

package main
import "fmt"
import "encoding/json"

type Response struct {
    Region string `json:"1"`
    Trends []string `json:"2"`
}

func main() {
    str := `{"1": ["apple", "banana"], "2": ["apple", "peach"]}`
    res := &Response{}
    json.Unmarshal([]byte(str), &res)
    fmt.Println(res.Trends)
}

我试图处理的JSON而不是str的当前值在这里:http://hawttrends.appspot.com/api/terms/

res.Trends是我想要的值我想把它们每个都写入。csv

JSON是畸形的,它应该返回一个数组而不是一个对象,但是你可以使用一个映射来实现你想要的:play

func main() {
    str := `{"1": ["apple", "banana"], "2": ["apple", "peach"]}`
    res := map[string][]string{}
    json.Unmarshal([]byte(str), &res)
    fmt.Println(res)
}

更新play:

func get_json(url string) []byte {
    resp, err := http.Get(url)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }
    return body
}
func main() {
    res := map[string][]string{}
    json.Unmarshal(get_json("http://hawttrends.appspot.com/api/terms/"), &res)
    for k, v := range res {
        fmt.Printf("%s=%#vn", k, v)
    }
}

我真的建议你看一下文档,它非常直接。

检查:

  1. http://tour.golang.org/# 1
  2. http://golang.org/pkg/net/http/

您需要首先以@OneOfOne建议的格式进行解析,然后将其放入您的结构中:

http://play.golang.org/p/A9TQ1d1Glt

package main
import (
    "encoding/json"
    "fmt"
    "strconv"
)
var data = `{...}`
type Response struct {
    Region int
    Trends []string
}
func main() {
    res := map[string][]string{}
    err := json.Unmarshal([]byte(data), &res)
    if err != nil {
        fmt.Println("Error:", err)
    }
    responses := make([]Response, len(res))
    i := 0
    for id, values := range res {
        id_int, err := strconv.Atoi(id)
        if err != nil {
            fmt.Println("Error for id:", id)
            continue
        }
        responses[i].Region = id_int
        responses[i].Trends = values
        i += 1
    }
    for i:=0; i < len(responses); i += 1{
        fmt.Printf("%#vn", responses[i])
    }
}

最新更新