英文:
How to Read JSON in Go Lang
问题
我有以下的JSON数组,通过使用CURL作为Web服务输出接收到。
{
"total_rows": 4,
"offset": 0,
"rows": [
{
"id": "_design/people",
"key": "_design/people",
"value": {
"rev": "3-d707964c8a3fa0c0c71e51c600bbafb8"
}
},
{
"id": "aamir",
"key": "aamir",
"value": {
"rev": "3-4b9095435470366fb77df1a3d466bcff"
}
},
{
"id": "iyaan",
"key": "iyaan",
"value": {
"rev": "1-4fea2c459d85480bf4841c7e581180c0"
}
},
{
"id": "tahir",
"key": "tahir",
"value": {
"rev": "2-593c9237a96836a98f53c0374902964a"
}
}
]
}
我想要将"total_rows"对象和"rows"对象分别提取出来。
英文:
I have the following JSON array received as a web service output using CURL.
{
"total_rows": 4,
"offset": 0,
"rows": [
{
"id": "_design/people",
"key": "_design/people",
"value": {
"rev": "3-d707964c8a3fa0c0c71e51c600bbafb8"
}
},
{
"id": "aamir",
"key": "aamir",
"value": {
"rev": "3-4b9095435470366fb77df1a3d466bcff"
}
},
{
"id": "iyaan",
"key": "iyaan",
"value": {
"rev": "1-4fea2c459d85480bf4841c7e581180c0"
}
},
{
"id": "tahir",
"key": "tahir",
"value": {
"rev": "2-593c9237a96836a98f53c0374902964a"
}
}
]
}
I want to extract the "total_rows" object separately from it and "rows" object separately.
答案1
得分: 1
你只需要使用encoding/json
包。
定义Row结构体:
type Row struct {
Id string `json:"id"`
Key string `json:"key"`
Value struct {
Rev string `json:"rev"`
} `json:"value"`
}
定义Data结构体:
type Data struct {
TotalRows int `json:"total_rows"`
Offset int `json:"offset"`
Rows []Row `json:"rows"`
}
然后使用json.Unmarshal
:
b := []byte("json string")
data := Data{}
if err := json.Unmarshal(b, &data); err != nil {
panic(err)
}
fmt.Println(data.TotalRows, data.Offset)
for _, row := range data.Rows {
fmt.Println(row.Id, row.Key)
}
以上是你要翻译的内容。
英文:
You just need the package encoding/json
.
Defined Row struct:
type Row struct {
Id string `json:"id"`
Key string `json:"key"`
Value struct {
Rev string `json:"rev"`
} `json:"value"`
}
Defined Data Sturct:
type Data struct {
TotalRows int `json:"total_rows"`
Offset int `json:"offest"`
Rows []Row `json:"rows"`
}
And then use json.Unmarshal
:
b := []byte("json string")
data := Data{}
if err := json.Unmarshal(b, &data); err != nil {
panic(err)
}
fmt.Println(data.TotalRows, data.Offset)
for _, row := range data.Rows {
fmt.Println(row.Id, row.Key)
}
答案2
得分: 0
如其他帖子中所建议的,"encoding/json"将为您提供所需的功能。我还建议尝试一些第三方库,因为它们可能更适合您的实现。最初,我建议您查看以下内容:
这只是一些快速建议,还有其他库可供选择。祝您好运!
英文:
As the other poster suggested, "encoding/json" will set you up with what you need. I will also recommend trying some of the third party libraries as they can maybe better fit your implementation. Initially I would suggest looking at:
These are just some quick suggestions and there are other libraries out there. Good luck!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论