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

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条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料