douduan9129
2016-06-20 01:39
浏览 50
已采纳

Golang中的Json解析

I am trying to parse a json from a third party software. It returns a json like this

{ 
   "top1/dir1": "10",
   "top1/dir2": "20",
   "top1/dir3": "30",
   "top2/diff_val1": "40"
}

JSONLint says this is a valid json. But I could not figure how I can parse this with golang.

The code I used to parse the json file above (to be clear I took the code from another stackoverflow post).

package main

import (
        "encoding/json"
        "fmt"
        "io/ioutil"
        "log"
)

type mytype []map[string]string

func main() {
        var data mytype
        file, err := ioutil.ReadFile("t1.json")
        if err != nil {
                log.Fatal(err)
        }
        err = json.Unmarshal(file, &data)
        if err != nil {
                log.Fatal(err)
        }
        fmt.Println(data)
}

When I do a go run main.go, I get the below error

$ go run main.go 2016/06/19 22:53:57 json: cannot unmarshal object into Go value of type main.mytype exit status 1

I did try to parse this format with another library - "github.com/Jeffail/gabs", but was unsuccessful. Since this is a valid json, I am pretty sure this can be parsed, but I am not sure how.

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

  • duanquan1876 2016-06-20 01:44
    最佳回答

    There is a Go package with methods for decoding JSON strings.

    https://golang.org/pkg/encoding/json/#Unmarshal

    Here is an example of usage:

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    func main() {
        var jsonBlob = []byte(`[
            {"Name": "Platypus", "Order": "Monotremata"},
            {"Name": "Quoll",    "Order": "Dasyuromorphia"}
        ]`)
        type Animal struct {
            Name  string
            Order string
        }
        var animals []Animal
        err := json.Unmarshal(jsonBlob, &animals)
        if err != nil {
            fmt.Println("error:", err)
        }
        fmt.Printf("%+v", animals)
    }
    

    EDIT: As pointed out by Malik, the type of the value whose pointer you pass is wrong. In this case, your type should be map[string]interface{} (preferably, because a JSON field might not store a string) or map[string]string instead of []map[string]string. The brackets at the beginning are wrong: such would be an array of JSON objects.

    评论
    解决 无用
    打赏 举报
查看更多回答(2条)

相关推荐 更多相似问题