Golang - 解析嵌套的JSON [英] Golang - Parsing nested JSON
问题描述
我正在使用去工作人员处理重新执行作业。一个作业有一个有效载荷,它具有如下的嵌套JSON结构: val-a,
key-b:val-b,
files:[{
key-a:[
{a :b,c:d},
{e:f,g:h}
],
key-b :[
{a:b,c:d},
{e:f,g:h}
]
}]
}]
现在 go -worker
给我 args ... interface {}
,它代表JSON有效负载,而不是实际的JSON文本。有没有一种习惯的方式将( args
)转换为正确的类型(可以使用另一个包来完成此操作)。手动使用类型断言似乎对于这样的事情有点乏味。
如果它真的给你实际的去对象(即一堆 map [string]接口{}
而不是json字符串本身),那么除了一些类型断言之外,你可以做的事情也不多。
你可以重新编组为json然后再解析它到正确的结构中,但这有点破解(我不知道它是否会高性能)。
I'm using the go-worker to process resque jobs. A job has a payload which has a nested JSON structure like this:
[{
"key-a":"val-a",
"key-b":"val-b",
"files":[{
"key-a": [
{"a":"b","c": "d"},
{"e":"f","g": "h"}
],
"key-b": [
{"a":"b","c": "d"},
{"e":"f","g": "h"}
]
}]
}]
Now go-worker
gives me args ...interface{}
which represents that JSON payload, not the actual JSON text. Is there an idiomatic way to convert that(args
) to the correct types (could use another package to do this.) Using type assertions manually seems a bit tedious for such a thing.
If it's really giving you the actual go objects (i.e. a bunch of map[string]interface{}
and not the json string itself) then there probably isn't much you can do besides a bunch of type assertions.
You could re-marshall it to json then parse it again into the correct structs, but that's a bit of a hack (and I have no idea if it would be performant or not).
这篇关于Golang - 解析嵌套的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!