JSON中的匿名字段

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

anonymous fields in JSON

问题

我正在逆向工程一些使用匿名字段名的JSON。例如:

{
   "1": 123,
   "2": 234,
   "3": 345
}

顺便说一下,它不仅仅使用"1"、"2"和"3",因为它们代表的是至少是int32类型的用户ID。

有没有一种方法,比如使用标签来正确地解析JSON?

我尝试过:

package main

import (
        "encoding/json"
        "fmt"
)

type MyStruct struct {
        string `json:",string"`
}

func main() {
        jsonData := []byte("{\"1\":123,\"2\":234,\"3\":345}")

        var decoded MyStruct
        err := json.Unmarshal(jsonData, &decoded)
        if err != nil {
                panic(err)
        }
        fmt.Printf("decoded=%+v\n", decoded)
}
英文:

I'm reverse engineering some JSON that seems to be using anonymous field names. For example:

{
   "1": 123,
   "2": 234,
   "3": 345
}

BTW - it's not simply using "1" and "2" and "3" because they represent userids that are at a minimum int32's.

Is there some way such as using tags to properly Unmarshal the JSON?

I've tried:

package main

import (
        "encoding/json"
        "fmt"
)

type MyStruct struct {
        string `json:",string"`
}

func main() {
        jsonData := []byte("{\"1\":123,\"2\":234,\"3\":345}")

        var decoded MyStruct
        err := json.Unmarshal(jsonData, &decoded)
        if err != nil {
                panic(err)
        }
        fmt.Printf("decoded=%+v\n", decoded)
}

答案1

得分: 4

只需将数据解码为一个映射(map[string]int):

jsonData := []byte("{\"1\":123,\"2\":234,\"3\":345}")

var decoded map[string]int
err := json.Unmarshal(jsonData, &decoded)
if err != nil {
    panic(err)
}

然后,您可以通过用户ID键迭代和访问元素:

for userID, _ := range decoded {
    fmt.Printf("User ID: %s\n", userID)
}

链接:https://play.golang.org/p/SJkpahGzJY

英文:

Just decode the data into a map (map[string]int):

jsonData := []byte("{\"1\":123,\"2\":234,\"3\":345}")

var decoded map[string]int
err := json.Unmarshal(jsonData, &decoded)
if err != nil {
    panic(err)
}

You'll then be able to iterate over and access the elements by the user ID key:

for userID, _ := range decoded {
	fmt.Printf("User ID: %s\n", userID)
}

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

huangapple
  • 本文由 发表于 2015年9月5日 08:18:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/32408249.html
匿名

发表评论

匿名网友

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

确定