英文:
golang Unmarshalling websocket-rails JSON response
问题
以下是翻译好的内容:
[
[
"client_connected",
{
"id": null,
"channel": null,
"user_id": null,
"data": {
"connection_id": null
},
"success": null,
"result": null,
"server_token": null
}
]
]
在这个来自 websocket-rails 服务器的 JSON 响应中,有一个没有任何键的字符串。我想知道解析这个的最佳方法是什么?
英文:
[
[
"client_connected",
{
"id": null,
"channel": null,
"user_id": null,
"data": {
"connection_id": null
},
"success": null,
"result": null,
"server_token": null
}
]
]
Given this JSON response from a websocket-rails server, I was wondering what the best way to parse this as there is a string without any key?
答案1
得分: 1
这不是最好的解决方案,但它是最简单的解决方案:
由于JSON输入不是方便的键值对(或其数组),我们不能只使用一个简单的struct
(这是理想的情况)来建模内容。
你的JSON输入是一个数组的数组。在其中有各种混合类型,所有这些类型都可以存储在空接口interface{}
中(它可以保存任何类型的值)。
因此,你可以用以下类型表示你的数据结构:
js := [][]interface{}{}
以下是解组它并打印它的完整代码:
js := [][]interface{}{}
err := json.Unmarshal([]byte(input), &js)
if err != nil {
panic(err)
}
fmt.Printf("%q", js)
输出(换行包装):
[["client_connected" map["server_token":<nil> "id":<nil> "channel":<nil>
"user_id":<nil> "data":map["connection_id":<nil>] "success":<nil> "result":<nil>]]]
在Go Playground上试一试。
注意:
看起来我们可以进一步简化,只使用interface{}
类型作为js
变量:
var js interface{}
这也可以工作,但在这种情况下,我们甚至需要类型断言来访问“包装器”数组的元素,这将是一个倒退。
英文:
This is not the best solution, but it is the simplest:
Since the JSON input is not the convenient key-value pairs (or arrays of that), we can't just use a simple struct
(which would be desirable) to model the content.
Your JSON input is an array of arrays. Inside that there are mixed types, all which can be stored in the empty interface interface{}
(which can hold a value of any type).
So you can represent your data structure with the type:
js := [][]interface{}{}
Here's the complete code to unmarshal it and print it:
js := [][]interface{}{}
err := json.Unmarshal([]byte(input), &js)
if err != nil {
panic(err)
}
fmt.Printf("%q", js)
Output (wrapped):
[["client_connected" map["server_token":<nil> "id":<nil> "channel":<nil>
"user_id":<nil> "data":map["connection_id":<nil>] "success":<nil> "result":<nil>]]]
Try it on the Go Playground.
Notes:
Seemingly we could simplify it further by just using interface{}
type for the js
variable:
var js interface{}
And it works too, but in this case we would need Type assertions even to just get to the elements of the "wrapper" arrays which would be a step back.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论