Golang – 解析嵌套的 JSON

huangapple go评论95阅读模式
英文:

Golang - Parsing nested JSON

问题

我正在使用go-worker来处理resque作业。作业有一个负载(payload),其中包含一个嵌套的JSON结构,如下所示:

[{
  "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"}
    ]
  }]
}]

现在,go-worker给我提供了一个表示JSON负载的args ...interface{},而不是实际的JSON文本。是否有一种惯用的方法将其(args)转换为正确的类型(可以使用另一个包来完成此操作)?对于这样的事情,手动使用类型断言似乎有点繁琐。

英文:

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.

答案1

得分: 1

如果它确实给你的是实际的go对象(即一堆map[string]interface{},而不是json字符串本身),那么除了进行一系列的类型断言之外,可能没有太多可以做的。

你可以将其重新编组为json,然后再次解析为正确的结构体,但这有点像是一个hack(我不知道它是否高效)。

英文:

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

huangapple
  • 本文由 发表于 2014年4月14日 23:02:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/23063517.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定