donglanzhan7151 2016-09-19 14:30
浏览 63
已采纳

Golang解析复杂的JSON

I am new to golang and json and currently struggle to parse the json out from a system.

I've read a couple of blog posts on dynamic json in go and also tried the tools like json2GoStructs Parsing my json file with this tools just gave me a huge structs which I found a bit messy. Also I had no idea how to get the info im interested in.

So, here are my problems:

  1. How do I get to the info I am interested in?
  2. What is the best approach to parse complex json?

I am only interested into the following 3 json fields:

Name
Guid
Task -> Property -> Name: Error

I'm thankful for every tip, code snippet or explanation!

This is what I got so far (mostly from a tutorial):

package main

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

func checkErr(err error) {
    if err != nil {
        panic(err)
    }
}

func readFile(filePath string) []byte {
    data, err := ioutil.ReadFile(filePath)
    checkErr(err)
    return data
}

func main() {
    path := "/Users/andi/Documents/tmp/wfsJob.json"
    data := readFile(path)

    var f interface{}

    err := json.Unmarshal(data, &f)
    checkErr(err)

    m := f.(map[string]interface{})

    for k, v := range m {
        switch vv := v.(type) {
        case string:
            fmt.Println(k, "is string", vv)
        case int:
            fmt.Println(k, "is int", vv)
        case []interface{}:
            fmt.Println(k, "is an array:")
            for i, u := range vv {
                fmt.Println(i, u)
            }
        default:
            fmt.Println(k, "is of a type I don't know how to handle")
        }
    }
}
  • 写回答

2条回答 默认 最新

  • dongtan9066 2016-09-19 15:39
    关注

    I can offer you this easy way to using JSON in Golang. With this tool you don't need to parse the whole json file, and you can use it without struct.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示