部分JSON解组到Go中的map中

92vpleto  于 2023-05-19  发布在  Go
关注(0)|答案(4)|浏览(157)

我的WebSocket服务器将接收并解组JSON数据。这些数据将始终 Package 在一个具有键/值对的对象中。键字符串将充当值标识符,告诉Go服务器它是什么类型的值。通过知道值的类型,我可以继续JSON将值解组为正确的结构类型。
每个JSON对象可能包含多个键/值对。
JSON示例:

{
    "sendMsg":{"user":"ANisus","msg":"Trying to send a message"},
    "say":"Hello"
}

有没有什么简单的方法可以使用"encoding/json"包来实现这一点?

package main

import (
    "encoding/json"
    "fmt"
)

// the struct for the value of a "sendMsg"-command
type sendMsg struct {
    user string
    msg  string
}
// The type for the value of a "say"-command
type say string

func main(){
    data := []byte(`{"sendMsg":{"user":"ANisus","msg":"Trying to send a message"},"say":"Hello"}`)

    // This won't work because json.MapObject([]byte) doesn't exist
    objmap, err := json.MapObject(data)

    // This is what I wish the objmap to contain
    //var objmap = map[string][]byte {
    //  "sendMsg": []byte(`{"user":"ANisus","msg":"Trying to send a message"}`),
    //  "say": []byte(`"hello"`),
    //}
    fmt.Printf("%v", objmap)
}

感谢您的任何建议/帮助!

pxq42qpu

pxq42qpu1#

这可以通过Unmarshaling到map[string]json.RawMessage来完成。

var objmap map[string]json.RawMessage
err := json.Unmarshal(data, &objmap)

要进一步解析sendMsg,您可以执行以下操作:

var s sendMsg
err = json.Unmarshal(objmap["sendMsg"], &s)

对于say,你可以做同样的事情,并解组成一个字符串:

var str string
err = json.Unmarshal(objmap["say"], &str)

**EDIT:**请记住,您还需要导出sendMsg结构中的变量以正确解封。所以你的struct定义应该是:

type sendMsg struct {
    User string
    Msg  string
}

示例:https://play.golang.org/p/OrIjvqIsi4-

uurity8g

uurity8g2#

这里有一个优雅的方式来做类似的事情。但是为什么JSON要部分解组呢?这说不通啊
1.为聊天创建结构体。
1.将json解码为struct。
1.现在你可以轻松地访问Struct/Object中的所有内容。
看看下面的工作代码。复制并粘贴它。

import (
   "bytes"
   "encoding/json" // Encoding and Decoding Package
   "fmt"
 )

var messeging = `{
"say":"Hello",
"sendMsg":{
    "user":"ANisus",
    "msg":"Trying to send a message"
   }
}`

type SendMsg struct {
   User string `json:"user"`
   Msg  string `json:"msg"`
}

 type Chat struct {
   Say     string   `json:"say"`
   SendMsg *SendMsg `json:"sendMsg"`
}

func main() {
  /** Clean way to solve Json Decoding in Go */
  /** Excellent solution */

   var chat Chat
   r := bytes.NewReader([]byte(messeging))
   chatErr := json.NewDecoder(r).Decode(&chat)
   errHandler(chatErr)
   fmt.Println(chat.Say)
   fmt.Println(chat.SendMsg.User)
   fmt.Println(chat.SendMsg.Msg)

}

 func errHandler(err error) {
   if err != nil {
     fmt.Println(err)
     return
   }
 }

Go playground

9jyewag0

9jyewag03#

除了Stephen温伯格的回答之外,我还实现了一个名为iojson的方便工具,它有助于轻松地将数据填充到现有对象中,并将现有对象编码为JSON字符串。还提供了一个iojson中间件来与其他中间件一起工作。更多示例可在https://github.com/junhsieh/iojson上找到

示例:

func main() {
    jsonStr := `{"Status":true,"ErrArr":[],"ObjArr":[{"Name":"My luxury car","ItemArr":[{"Name":"Bag"},{"Name":"Pen"}]}],"ObjMap":{}}`

    car := NewCar()

    i := iojson.NewIOJSON()

    if err := i.Decode(strings.NewReader(jsonStr)); err != nil {
        fmt.Printf("err: %s\n", err.Error())
    }

    // populating data to a live car object.
    if v, err := i.GetObjFromArr(0, car); err != nil {
        fmt.Printf("err: %s\n", err.Error())
    } else {
        fmt.Printf("car (original): %s\n", car.GetName())
        fmt.Printf("car (returned): %s\n", v.(*Car).GetName())

        for k, item := range car.ItemArr {
            fmt.Printf("ItemArr[%d] of car (original): %s\n", k, item.GetName())
        }

        for k, item := range v.(*Car).ItemArr {
            fmt.Printf("ItemArr[%d] of car (returned): %s\n", k, item.GetName())
        }
    }
}

输出示例:

car (original): My luxury car
car (returned): My luxury car
ItemArr[0] of car (original): Bag
ItemArr[1] of car (original): Pen
ItemArr[0] of car (returned): Bag
ItemArr[1] of car (returned): Pen
dauxcl2d

dauxcl2d4#

简单的flat json来Map:例如json:

{
 "was": {
  "username": "userwas",
  "password": "pwdwas",
  "secret": "secretwas"
 },
 "ynb": {
  "username": "userynb",
  "password": "pwdynb",
  "secret": "secterynb"
 }
}

好的,创建结构体:

type HostData struct {
    Username string `json:"username"`
    Password string `json:"password"`
    Secret   string `json:"secret"`
}

主要功能:

func main() {
    // Example as []byte
    data := []byte(
        `{
        "ynb": {
            "username": "userynb",
            "password": "pwdynb",
            "secret": "secterynb"
        },
        "was":{
            "username": "userwas",
            "password": "pwdwas",
            "secret": "secretwas"
        }
    }`)

    var objmap map[string]json.RawMessage
    err := json.Unmarshal(data, &objmap)
    if err != nil {
        log.Fatal(err)
    }

    var hostDataMap map[string]HostData = make(map[string]HostData)
    // find keys and fill out the map
    for key := range objmap {
        var hd HostData
        err = json.Unmarshal(objmap[key], &hd)
        if err != nil {
            log.Fatal(err)
            return
        }
        hostDataMap[key] = hd
    }

    // Output map:
    fmt.Println(hostDataMap)
    // Output:
    // map[was:{userwas pwdwas secretwas} ynb:{userynb pwdynb secterynb}]
    / or if:
    //fmt.Println(hostDataMap["was"].Username)
    // Output: userwas
}

返回到json的完整代码:https://go.dev/play/p/qocCW_rAnAL

相关问题