skip to Main Content

I have following JSON:

{
    "common": {
        "a": "xyz",
        "b": "qwe"
    },
    "events": [
        {
            "c": "lll",
            "?": "eee",
            "??": "ppp"

        }
    ]
}

I know that it has the "a", "b" and "c" fields but I don’t know the names of other fields. I want to unmarshal it in the following structure:

type Request struct {
    Common CommonParams `json:"common"`
    Events []Event      `json:"events"`
}

type CommonParams struct {
    A string `json:"a"`
    B string `json:"b"`
}

type Event struct {
    C string                 `json:"c"`
    X map[string]interface{} `json:?????`
}

How do I do that?

The solutions here don’t work as the fields in this JSON are in a nested structure.

2

Answers


  1. maybe you can use this?

    var res map[string]any
    err := json.Unmarshal([]byte(j), &res)
    if err != nil {
        panic(err)
    }
    

    and use loop for extract unknow fields like this

    if events, ok := res["events"].([]any); ok {
        for _, event := range events {
            if eventMap, ok := event.(map[string]any); ok {
                for key, value := range eventMap {
                    fmt.Printf("Field: %s, Value: %vn", key, value)
                }
            }
        }
    }
    
    Login or Signup to reply.
  2. jsonData := `{
        "common": {
            "a": "xyz",
            "b": "qwe"
        },
        "events": [
            {
                "c": "lll",
                "?": "eee",
                "??": "ppp"
            }
        ]
    }`
    
    var req map[string]interface{}
    if err := json.Unmarshal([]byte(jsonData), &req); err != nil {
        fmt.Println("Error unmarshalling JSON:", err)
        return
    }
    
    // Extract common params
    commonMap := req["common"].(map[string]interface{})
    commonParams := CommonParams{
        A: commonMap["a"].(string),
        B: commonMap["b"].(string),
    }
    
    // Extract events
    eventsMap := req["events"].([]interface{})
    events := make([]Event, len(eventsMap))
    for i, eventInterface := range eventsMap {
        eventMap := eventInterface.(map[string]interface{})
        event := Event{
            C: eventMap["c"].(string),
            X: make(map[string]interface{}),
        }
        for key, value := range eventMap {
            if key != "c" {
                event.X[key] = value
            }
        }
        events[i] = event
    }
    
    // Construct the final Request struct
    finalReq := &Request{
        Common: commonParams,
        Events: events,
    }
    
    fmt.Printf("Unmarshalled Request: %+vn", finalReq)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search