使用Golang解析JSON字符串

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

Unmarshalling JSON string with Golang

问题

我有以下的 JSON 字符串:

{"x":{"l.a":"test"}}

type Object struct {
    Foo  map[string]map[string]string `json:"l.a"`
}
var obj Object
err = json.Unmarshal(body, &obj)
if err != nil{
    fmt.Println(err)
}
fmt.Println("jsonObj", obj)

但是得到了空值,有什么办法可以获取字符串 "test" 吗?

英文:

I have the following json string

{"x":{"l.a":"test"}}

type Object struct {
    Foo  map[string]map[string]string `json:"l.a"`
}
var obj Object
err = json.Unmarshal(body, &obj)
if err != nil{
    fmt.Println(err)
}
fmt.Println("jsonObj", obj)

but get empty any idea how can i get the string "test"

答案1

得分: 2

使用您的代码,Unmarshal 在 JSON 的顶层查找 l.a(但它不存在 - x 存在)。

有几种方法可以修复这个问题,最好的方法将取决于您的最终目标;以下是其中几种方法(playground):

const jsonTest = `{"x":{"l.a":"test"}}`

type Object struct {
	Foo map[string]string `json:"x"`
}

func main() {
	var obj Object
	err := json.Unmarshal([]byte(jsonTest), &obj)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("jsonObj", obj)

	var full map[string]map[string]string
	err = json.Unmarshal([]byte(jsonTest), &full)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("jsonObj2", full)
}

(在输入时接到了电话,看到 @DavidLilue 提供了类似的评论,但还是决定发布这个回答)。

英文:

With your code Unmarshal is looking for l.a at the top level in the JSON (and it's not there - x is).

There are a number of ways you can fix this, the best is going to depend upon your end goal; here are a couple of them (playground)

const jsonTest = `{"x":{"l.a":"test"}}`

type Object struct {
	Foo map[string]string `json:"x"`
}

func main() {
	var obj Object
	err := json.Unmarshal([]byte(jsonTest), &obj)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("jsonObj", obj)

	var full map[string]map[string]string
	err = json.Unmarshal([]byte(jsonTest), &full)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("jsonObj2", full)

}

(Got a phone call while entering this and see @DavidLilue has provided a similar comment but may as well post this).

答案2

得分: 1

你可以始终创建一个结构体来解析你的 JSON。

type My_struct struct {
	X struct {
		LA string `json:"l.a"`
	} `json:"x"`
}

func main() {
	my_json := `{"x":{"l.a":"test"}}`
	var obj My_struct
	json.Unmarshal([]byte(my_json), &obj)
	fmt.Println(obj.X.LA)
}

在这里,你创建了一个结构体,然后将 JSON 字符串解析为该结构体的对象,所以当你执行 obj.X.LA 时,你将得到字符串 "test"。

英文:

You can always create a struct to unmarshall your json

type My_struct struct {
	X struct {
		LA string `json:"l.a"`
	} `json:"x"`
}

func main() {
	my_json := `{"x":{"l.a":"test"}}`
	var obj My_struct
	json.Unmarshal([]byte(my_json), &obj)
	fmt.Println(obj.X.LA)
}

here you are creating a struct and then unmarshalling your json string to its object, so when you do obj.X.LA you will get the string

huangapple
  • 本文由 发表于 2022年9月9日 09:28:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/73656452.html
匿名

发表评论

匿名网友

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

确定