json - 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
解决方案
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]]}
}
推荐阅读
- python - 如何控制numpy数组的保留容量?
- c# - C# 简单的垃圾回收代码不起作用
- flutter - Flutter TextField ScrollBar 下边距
- python - 如何使用 Python 从字符串中提取特定路径?
- visual-studio-code - 我可以将 VS Code 配置为具有多个实例,例如处理不同的项目吗?
- python - 尝试使用 Pycharm 生成的套接字来拉取同一目录中的 HTML 文件的内容
- types - 来自记录规则的 Prometheus 指标
- windows - Active Directory 存储的加入域的 Windows 计算机的 objectGUID 或 ObjectSID 是否也存储在本地?
- python - 如何使用 Python 在 Anki Deck 上放置卡片
- python - ModuleNotFoundError:没有名为“SessionState”的模块