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 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了
  • ¥15 微信小程序商城如何实现多商户收款 平台分润抽成
  • ¥15 HC32L176调试了一个通过TIMER5+DMA驱动WS2812B
  • ¥15 cocos的js代码调用wx.createUseInfoButton问题!
  • ¥15 关于自相关函数法和周期图法实现对随机信号的功率谱估计的matlab程序运行的问题,请各位专家解答!
  • ¥15 Python程序,深度学习,有偿私
  • ¥15 扫描枪扫条形码出现问题
  • ¥35 poi合并多个word成一个新word,原word中横版没了.
  • ¥15 【火车头采集器】搜狐娱乐这种列表页网址,怎么采集?