dsvs50005 2017-12-12 07:29
浏览 590

在golang中构造复杂的JSON解析

I have a valid JSON, which I don't know how to parse in json.Unmarshal (golang):

{
   "method": "notice",
   "params": [0, [{
           "previous": "12345",
           "timestamp": "2017-12-12T05:49:09",
           "witness": "12345",
           "transaction_merkle_root": "ffff",
           "extensions": [],
           "witness_signature": "12345"
   }]]
}

All I can do is:

type MyJSON struct {
    Method string        `json:"method"`
    Params []interface{} `json:"params"`
}

I will be really thankful if somebody help me to write correct MyJSON type to parse all other fields through golang's json.Unmarshal. It's way too complex to me :(

  • 写回答

2条回答 默认 最新

  • douju1280 2017-12-12 08:04
    关注

    I assume that params depends on the method. If so, start by decoding the top-level to a struct with the method name and a json.RawMessage to collect the parameters as JSON text.

    var call struct {
        Method string
        Params json.RawMessage
    }
    if err := json.Unmarshal(data, &call); err != nil {
        log.Fatal(err)
    }
    

    Declare variables for each parameter. This code will depend on the method.

        var param0 int
        var param1 []struct {
            Previous                string
            Timestamp               string
            Witness                 string
            Transaction_merkle_root string
            Extensions              []interface{}
            Witness_signature       string
        }
    

    Create a parameter list using pointers to those variables.

        params := []interface{}{&param0, &param1}
    

    Now unmarshal the JSON to params. This will set the variables param0 and param1:

        if err := json.Unmarshal(call.Params, &params); err != nil {
            log.Fatal(err)
        }
    

    Repeat for other methods.

    Here's the runnable code on the playground.

    This can be simplified if you will only need to handle the "notice" method. In this case, you can decode directly to the parameters without the RawMessage step.

    var param0 int
    var param1 []struct {
        Previous                string
        Timestamp               string
        Witness                 string
        Transaction_merkle_root string
        Extensions              []interface{}
        Witness_signature       string
    }
    call := struct {
        Method string
        Params []interface{}
    }{
        Params: []interface{}{&param0, &param1},
    }
    
    if err := json.Unmarshal(data, &call); err != nil {
        log.Fatal(err)
    }
    

    Here's runnable code for the simple case.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。