使用Go语言保存Json数据

时间:2017-07-02 14:49:53

标签: go

我正在尝试解析Json&使用GO语言将Student Pecentage保存到csv文件。

使用以下代码,我可以打印并保存Rollno。并成功地在csv中标记。

package main

import (
    "encoding/csv"
    "fmt"
    "net/http"
    "os"
)

func PageRequest(w http.ResponseWriter, r *http.Request) {
    // Default page number is 1
    if len(r.URL.Path) <= 1 {
        r.URL.Path = "/1"
    }

    // Page number is not negative or 0
    page.Abs(page)
    if page.Cmp(one) == -1 {
        page.SetInt64(1)
    }

    // Page header
    fmt.Fprintf(w, PageHeader, pages, previous, next)

    // Save in csv
    csvfile, err := os.OpenFile("marks.csv", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    defer csvfile.Close()

    writer := csv.NewWriter(csvfile)
    defer writer.Flush()

    // Marks for UID
    UID, length := compute(start)
    for i := 0; i < length; i++ {
        key := UID[i]

        fmt.Fprintf(w, key.fname, key.marks, key.rollno) 



        records := [][]string{{key.fname, key.marks, key.rollno}}

        for _, record := range records {
            err := writer.Write(record)
            if err != nil {
                fmt.Println("Error:", err)
                return
            }
        }


    }

    // Page Footer
    fmt.Fprintf(w, PageFooter, previous, next)
}

这就是我正在做的事情

  1. 访客访问studentmarks.com/page=1 RollNo。 &安培;显示10名学生的成绩,并以CSV格式保存[与上述代码完美配合]

  2. 它向studentpercentagejson.com/Roll1,Roll2,Roll3发出请求(我们在第1步中获得的所有RollNo。) Json的回应就像

    [{"name":"James","Percentage":96.5,"RollNo":101}, 
    {"name":"William","Percentage":36.0,"RollNo":102}, 
    {"name":"Jacob","Percentage":63.0,"RollNo":103}, 
    {"name":"Wilson","Percentage":69.3,"RollNo":104}, 
    {"name":"Kurtson","Percentage":16.9,"RollNo":105}, 
    {"name":"Tom","Percentage":86.3,"RollNo":106}]
    
  3. Extract Name&amp;百分比字段&amp;保存在csv。

  4. 到目前为止的进展 -

    package main
    
    import (
        "encoding/json"
        "fmt"
        "net/http"
    )
    
    type object []struct {
        Name       string  `json:"name"`
        Percentage float64 `json:"Percentage"`
        RollNo     int     `json:"RollNo"`
    }
    
    func main() {
    http.HandleFunc("/", PageRequest)
        res, err := http.Get("https://studentpercentagejson.com/key.rollno")
        if err != nil {
            panic(err.Error())
        }
        defer res.Body.Close()
    
    
        err = json.NewDecoder(res.Body).Decode(&s)
        if err != nil {
            fmt.Println("whoops:", err)
        }
    log.Println("Listening")
    log.Fatal(http.ListenAndServe(":8080", nil))
    }
    

    如何使用go语言打印并保存从JSON响应中提取的百分比?

1 个答案:

答案 0 :(得分:0)

我不明白你在使用服务器API做什么。但我回答了如何从http响应中解码JSON。

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
)

type object []struct {
}

type ObjectsAPIResponse struct {
    Allmarks []object
}

func main() {
    res, err := http.Get("https://studentpercentagejson.com/key.rollno")
    if err != nil {
        panic(err.Error())
    }
    defer res.Body.Close()

    var s ObjectsAPIResponse
    err = json.NewDecoder(res.Body).Decode(&s)
    if err != nil {
        fmt.Println("whoops:", err)
    }
    fmt.Println(s.Allmarks)
}

收集RollNo(s)

var rollNos []string
for i := 0; i < length; i++ {
    key := UID[i]

    fmt.Fprintf(w, key.fname, key.marks, key.rollno) 

    records := [][]string{{key.fname, key.marks, key.rollno}}

    rollNos = append(rollNos, key.rollno)

    for _, record := range records {
        err := writer.Write(record)
        if err != nil {
            fmt.Println("Error:", err)
            return
        }
    }
}
uri := "http://studentpercentagejson.com/" + strings.Join(rollNos, ",")
res, err := http.Get(uri)
if err != nil {
    log.Fatal(err)
}
defer res.Body.Close()

var s ObjectsAPIResponse
err = json.NewDecoder(res.Body).Decode(&s)
if err != nil {
    log.Fatal(err)
}
fmt.Println(s.Allmarks[0].Name)
fmt.Println(s.Allmarks[0].Percentage)
fmt.Println(s.Allmarks[0].RollNo)