2
votes

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

2 Answers

3
votes

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.

0
votes

Try using fastjson. It is able to parse and query arbitrary JSON without defining additional structs and without code generation:

var p fastjson.Parser
v, err := p.Parse(data)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("method=%s", v.GetStringBytes("method"))

// GetStringBytes accepts a path of keys to extract json value.
// Array indexes must be passed as decimal strings.
fmt.Printf("timestamp=%s", v.GetStringBytes("params", "1", "0", "timestamp"))