如何将JSON解析为数据结构?

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

How to parse JSON into data structure

问题

我正在尝试解析以下类型的JSON数据:

"{\"ids\":[\"a\",\"b\"]}"

以下是我的代码:

package main

import "fmt"
import "encoding/json"
import "strings"

type Idlist struct {
    id []string `json:"ids"`
}
func main() {
    var val []byte = []byte(`"{\"ids\":[\"a\",\"b\"]}"`)
    jsonBody, _ := strconv.Unquote(string(val))

    var holder Idlist
    if err := json.NewDecoder(strings.NewReader(jsonBody)).Decode(&holder); err!= nil{
        fmt.Print(err)
    }
    fmt.Print(holder)
    fmt.Print(holder.id)
}

然而,我一直得到以下输出:

{[]}[]

我无法获取结构中的数据。
我做错了什么?这是playground链接:https://play.golang.org/p/82BaUlfrua

英文:

I am trying to parse a JSON of the type

"{\"ids\":[\"a\",\"b\"]}"

Here is my code:

package main

import "fmt"
import "encoding/json"
import "strings"

type Idlist struct {
    id []string `json:"ids"`
}
func main() {
    var val []byte = []byte(`"{\"ids\":[\"a\",\"b\"]}"`)
    jsonBody, _ := strconv.Unquote(string(val))

	var holder Idlist
    if err := json.NewDecoder(strings.NewReader(jsonBody)).Decode(&holder); err!= nil{
	    fmt.Print(err)
	}
    fmt.Print(holder)
	fmt.Print(holder.id)
}

However, I keep getting output

{[]}[]

I cannot get the data in the structure.
Where am I going wrong? Here is the playground link: https://play.golang.org/p/82BaUlfrua

答案1

得分: 1

你的结构体应该像这样:

type Idlist struct {
    Id []string `json:"ids"`
}

Golang假设以大写字母开头的字段是公开的。因此,你的字段对于JSON解码器来说是不可见的。更多详情请参考这篇帖子:
https://stackoverflow.com/questions/21825322/why-golang-cannot-generate-json-from-struct-with-front-lowercase-character

英文:

Your struct has to look like :

type Idlist struct {
    Id []string `json:"ids"`
}

Golang assumes that the fields starting with capital case are public. Hence, your fields are not visible to json decoder. For more details please look into this post :
https://stackoverflow.com/questions/21825322/why-golang-cannot-generate-json-from-struct-with-front-lowercase-character

答案2

得分: 0

这是一个解决你问题的示例:http://play.golang.org/p/id4f4r9tEr

你可能需要在字符串上使用strconv.Unquote

这可能是一个重复的问题:https://stackoverflow.com/questions/16846553/how-to-unmarsal-escaped-json-string-on-go

已解决:https://play.golang.org/p/hAShmfDUA_

type Idlist struct {
    Id []string `json:"ids"`
}
英文:

This is example how you can resolve your problem: http://play.golang.org/p/id4f4r9tEr

You might need to use strconv.Unquote on your string.

And this is probably duplicate: https://stackoverflow.com/questions/16846553/how-to-unmarsal-escaped-json-string-on-go

Resolved: https://play.golang.org/p/hAShmfDUA_

type Idlist struct {
    Id []string `json:"ids"`
}

huangapple
  • 本文由 发表于 2015年11月25日 17:14:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/33912505.html
匿名

发表评论

匿名网友

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

确定