尝试将 JSON 转换为 Golang Web 应用程序中的 Map。

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

Try to convert json to map for golang web application

问题

我正在使用golang编写一个Web应用程序。这个应用程序试图使用gitea的API。我的任务是获取JSON并将其转换为map。首先,我使用ioutil.ReadAll()将response.body转换为[]byte,然后使用Unmarshal()将其转换为map。我可以得到以[]byte格式的response.body。然而,map中没有元素。有人知道原因吗?

你可以看到map是空的,但我可以得到以[]byte格式的response.Body。

尝试将 JSON 转换为 Golang Web 应用程序中的 Map。

尝试将 JSON 转换为 Golang Web 应用程序中的 Map。

英文:

I am writing a web application using golang. This app tries to use the api of gitea. My task is to get json and convert it to map. First I get the response.body and convert it to []byte by using ioutil.readAll(), then I use Unmarshal() to convert it to map. I can get the response.body in []byte format. However, there is no element in map. Does anyone know the reason?

尝试将 JSON 转换为 Golang Web 应用程序中的 Map。

尝试将 JSON 转换为 Golang Web 应用程序中的 Map。

you can see that the map is empty but I can get response.Body in []byte format.

答案1

得分: 3

你展示的responseData字节转储图片中,数组中的第一个整数值是91。在ASCII码中,它是一个左方括号[,或者说是一个数组的开始。第二个字节123是一个左花括号{

解码你的前几个字节:

[{"id":3,"url":"http://...

因此,你的响应体不是一个JSON对象,而更可能是一个包含JSON对象的JSON数组。

请改用以下方法:

var items []interface{}
err := json.Unmarshal(responseData, &items)

如果一切顺利,你的items数组将被填充为一组map[string]interface{}实例。这假设数组中的所有项都是JSON对象。

如果你确定它总是一个对象数组,你可以将items声明为以下形式(一个map的数组)。

var items []map[string]interface{}
英文:

Your picture that shows the dump of responseData byte, the first integer value in that array is 91. In ascii, that's a left bracket, [, or rather the start of an array. The second byte, 123, is a left curly brace, or {

Decoding your first few bytes:

[{"id":3,"url":"http://...

Hence, your response body is not a json object, but rather it's more likely to be a json array containing json objects.

Do this instead:

var items []interface{}
err := json.Unmarshal(responseData, &items)

If all goes well, your items array is filled up with an array of map[string]interface{} instances. That assumes that all items in the array are json objects to begin with.

And if you know for certain that it's always an array of objects, you can declare items as this instead (an array of maps).

var items []map[string]interface{}

huangapple
  • 本文由 发表于 2022年4月18日 11:13:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/71907261.html
匿名

发表评论

匿名网友

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

确定