duanli12176
duanli12176
2014-04-14 15:02
浏览 128
已采纳

Golang-解析嵌套的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.

图片转代码服务由CSDN问答提供 功能建议

我正在使用上班族来处理预定工作。 作业的有效负载具有这样的嵌套JSON结构:

  [{
“ key-a”:“ val-a”,
“ key-b  “:” val-b“,
”文件“:[{
” 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 )转换为正确的类型(可以使用另一个包来完成此操作。)手动使用类型断言对于这种事情似乎有点乏味。 \ n

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dto5637
    dto5637 2014-04-14 15:40
    已采纳

    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).

    点赞 评论

相关推荐