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

时间:2014-06-04 01:07:52

标签: json csv go

我目前能够解码程序内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

2 个答案:

答案 0 :(得分:1)

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=%#v\n", k, v)
    }
}

我真的建议你阅读文档,这是非常直接的。

检查:

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

答案 1 :(得分:0)

您需要先以@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("%#v\n", responses[i])
    }
}