json - 如何解码/存储未知的 json 字段?

标签 json go

我需要从第 3 方 API 中解码 json。虽然我知道响应类型,但我需要确保我不会丢失 API 可能引入的任何字段(api 没有文档),所以我想知道我该怎么做。理想情况下,我想将未知字段存储在 interface{} 值中,并可能对其进行编码以供以后审核。到目前为止,这是我尝试过的方法,但它不起作用(编译时“未知”的 Data 字段在解码期间丢失)。

Play

package main

import (
    "encoding/json"
    "fmt"
)

type Tweet struct {
    User_id int
    Message string
    Unknown
}
type Unknown map[interface{}]interface{}

func main() {
    // Define an empty interface
    var t Tweet

    // Convert JSON string into bytes
    b := []byte(`{"user_id": 1, "message": "Hello world", "Date": "somerandom date"}`)

    // Decode bytes b into interface i
    json.Unmarshal(b, &t)
    fmt.Println(t)
}

最佳答案

您可以按照 inf 的建议使用 RawMessage。这是一个使用 sharktanklabs j2n package 的示例.

package main

import (
    "encoding/json"
    "fmt"

    "github.com/sharktanklabs/j2n"
)

type TweetData struct {
    User_id  int
    Message  string
    Overflow map[string]*json.RawMessage `json:"-"`
}

type Tweet struct {
    TweetData
}

func (c *Tweet) UnmarshalJSON(data []byte) error {
    return j2n.UnmarshalJSON(data, &c.TweetData)
}

func (c Tweet) MarshalJSON() ([]byte, error) {
    return j2n.MarshalJSON(c.TweetData)
}

func main() {
    // Define an empty interface
    var t Tweet

    // Convert JSON string into bytes
    b := []byte(`{"user_id": 1, "message": "Hello world", "Date": "somerandom date"}`)

    // Decode bytes b into interface i
    json.Unmarshal(b, &t)
    fmt.Printf("%#v\n", t)
}
// Formatted output: 
//     main.Tweet{TweetData:main.TweetData{
//         User_id:1, 
//         Message:"Hello world",     
//         Overflow:map[string]*json.RawMessage{
//             "user_id":(*json.RawMessage)(0xc82000e340), 
//             "message":(*json.RawMessage)(0xc82000e3c0), 
//             "Date":(*json.RawMessage)(0xc82000e440)}}}

关于json - 如何解码/存储未知的 json 字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32425866/

相关文章:

如果值存在,Python 从 json 中删除元素

json - 如何在网站页面上显示 Shopify 购物车值(Shopify 网站之外)

postgresql - 如何将 pq.Int64Array 转换为字符串?

json - Docusign API 使用模板和模板中的自定义字段未通过 HttpRequest 填充

javascript - js中将Array转为Jsondata对象的对象

php - 使用 jQuery 通过 AJAX 将 JSON 发送到 PHP

java - 如何更新 JSONB 列 postgres JDBC?

go - 更新 crypto-config.yaml 文件并在网络中更新

mongodb - 如何向 bson.D 对象添加值

http - (Go)发送http请求时如何控制gzip压缩?