首页 > 解决方案 > Parse (arbitrary) previously know data from JSON using GO

问题描述

I have to parse some JSON files.
The problem is: the type of data some field contains varies according some external (already obtained) information.
My question is: how do I perform this using golang? I've looked for a solution for this for hours and tried coming up with one, but I keep getting runtime errors.
Also, I thought the type coercion/casting would work based on this post.

I am quite a newbie regarding that language, so I ask you for not being too harsh answering this.

package main

import (
    "encoding/json"
    "fmt"
    "reflect"
    "unsafe"
)

func main() {
    birdJson := `{
            "blah": "bleh",
            "coord" : [[1,2], [3, 4], [22, 5]]
        }
    `
    var result map[string]interface{}
    json.Unmarshal([]byte(birdJson), &result)
    fmt.Println("result:: ", result)

    c := result["coord"]
    
    cv := reflect.ValueOf(c)
    ct := reflect.TypeOf(c)

    fmt.Println("c value:", cv)
    fmt.Println("c type: ", ct)
    fmt.Println(cv.Interface().([][]int))
}

The output:

result::  map[blah:bleh coord:[[1 2] [3 4] [22 5]]]
c value: [[1 2] [3 4] [22 5]]
c type:  []interface {}
panic: interface conversion: interface {} is []interface {}, not [][]int

goroutine 1 [running]:
main.main()
    /Users/maffei/golab/t.go:27 +0x497
exit status 2

标签: jsongoparsing

解决方案


It's not really clear what you're trying to do, but you can Unmarshal like this:

package main

import (
   "encoding/json"
   "fmt"
)

var birdJson = []byte(`
{
   "blah": "bleh", "coord" : [
      [1,2], [3, 4], [22, 5]
   ]
}
`)

func main() {
   var result struct {
      Blah string
      Coord [][]int
   }
   json.Unmarshal(birdJson, &result)
   fmt.Printf("%+v\n", result) // {Blah:bleh Coord:[[1 2] [3 4] [22 5]]}
}

推荐阅读