读取在线的 JSON 数据并将值保存到 Golang 中的 CSV 文件中。

huangapple go评论86阅读模式
英文:

read online JSON and save values to CSV in Golang

问题

我目前能够解码程序中的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文件中。

英文:

I'm am currently able to decode in-programme JSON.

However, I want to decode online JSON and save some values as values in a CSV file.

Here is my current code: 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)
}

The JSON I'm trying to process instead of the current-value of str is here: http://hawttrends.appspot.com/api/terms/

res.Trends are the values that I want and I want to take each of them and write them to a .csv

答案1

得分: 1

那个 JSON 格式不正确,应该返回一个数组而不是一个对象,但是你可以使用 map 来实现你想要的效果: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/
英文:

That JSON is malformed, it should return an array not an object, however you can use a map to achieve what you want : play

func main() {

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

Update 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)
	}
}

I really recommend you go through the documentation, it's very straight forward.

Check :

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

答案2

得分: 0

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

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])
	}
}

请注意,这是一段Go语言代码,用于将JSON数据解析为结构体。

英文:

You need to parse first in the format that @OneOfOne suggested and then put it inside your structure:

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

package main

import (
	&quot;encoding/json&quot;
	&quot;fmt&quot;
	&quot;strconv&quot;
)

var data = `{...}`

type Response struct {
	Region int
	Trends []string
}

func main() {
	res := map[string][]string{}
	err := json.Unmarshal([]byte(data), &amp;res)
	if err != nil {
		fmt.Println(&quot;Error:&quot;, err)
	}
	responses := make([]Response, len(res))
	i := 0
	for id, values := range res {
		id_int, err := strconv.Atoi(id)
		if err != nil {
			fmt.Println(&quot;Error for id:&quot;, id)
			continue
		}
		responses[i].Region = id_int
		responses[i].Trends = values
		i += 1
	}
	
	for i:=0; i &lt; len(responses); i += 1{
		fmt.Printf(&quot;%#v\n&quot;, responses[i])
	}
}

huangapple
  • 本文由 发表于 2014年6月4日 09:07:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/24027430.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定