How can I parse []int JSON data in Go?

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

How can I parse []int JSON data in Go?

问题

我尝试解析包含整数数组的JSON数据。但是,我无法获取整数数组。

package main
import (
	"encoding/json"
	"fmt"
)

type Anything struct {
	A []int `json:"a"`
}

func main() {
	s := "{a:[1,2,3]}"

	var a Anything
	json.Unmarshal([]byte(s), &a)
	fmt.Println(a.A)
}

我得到了一个空数组。

[]

我该如何获取[1, 2, 3]

英文:

I try parse JSON data include integer array. But, I can't get integer array.

package main
import (
	"encoding/json"
	"fmt"
)

type Anything struct {
	A []int `json:"a"`
}

func main() {
	s := "{a:[1,2,3]}"

	var a Anything
	json.Unmarshal([]byte(s), &a)
	fmt.Println(a.A)
}

I got empty array.

[]

How can I get [1, 2, 3]?

答案1

得分: 2

{a:[1,2,3]} 不是有效的 JSON。对象的键必须使用双引号引起来。将其更改为以下形式可以正常工作:

s := "{\"a\":[1,2,3]}"

https://play.golang.org/p/qExZAeiRJy

英文:

{a:[1,2,3]} is not valid JSON. Object keys must be double-quoted. Changing it like this works as expected:

s := "{\"a\":[1,2,3]}"

https://play.golang.org/p/qExZAeiRJy

答案2

得分: 1

你的JSON格式是无效的。你应该进行替换,例如像这样:s := [{"a":[1,2,3]}] 或者像这样 s := "[{\"a\":[1,2,3]}]"

你可以将你的代码编辑成以下形式:

package main

import (
    "encoding/json"
    "fmt"
)


type Anything struct {
    A []int `json:"a"`
}


func main() {
    // 注意这里:`[{"a":[1,2,3]}]`
    // 或者:s := "[{\"a\":[1,2,3]}]"
    s := `[{"a":[1,2,3]}]`

    var a []Anything
    json.Unmarshal([]byte(s), &a)
    fmt.Println(a)
}

输出结果:

[{[1 2 3]}]

你可以在 https://play.golang.org/p/H4GupGFpfP 上运行它。

英文:

You have an invalid JSON. You should replace it, for example like this: s := [{"a":[1,2,3]}] or maybe like this s := "[{\"a\":[1,2,3]}]".

You can edit your code to something like this:

package main

import (
    "encoding/json"
    "fmt"
)


type Anything struct {
    A []int `json:"a"`
}


func main() {
    // note here: `[{"a":[1,2,3]}]`
    // or: s := "[{\"a\":[1,2,3]}]"
    s := `[{"a":[1,2,3]}]`

    var a []Anything
    json.Unmarshal([]byte(s), &a)
    fmt.Println(a)
}

Output:

[{[1 2 3]}]

You can run it on https://play.golang.org/p/H4GupGFpfP

huangapple
  • 本文由 发表于 2017年2月7日 07:30:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/42079174.html
匿名

发表评论

匿名网友

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

确定