0

I have a JSON of below structure:

[
    {
        "option_id": "cust_info",
        "value_type": "JSON",
        "value": {
            "validForVerification": true,
            "firstLetter": "S",
            "lastLetter": "I"
        }
    },
    {
        "option_id": "settings_show_image",
        "value_type": "Boolean",
        "value": 1
    },
    {
        "option_id": "bonus_disabled_notified",
        "value_type": "Boolean",
        "value": false
    },
    {
        "option_id": "free_mugs_limit",
        "value_type": "Integer",
        "value": -1
    },
    {
        "option_id": "leaderboard_notification",
        "value_type": "Integer",
        "value": 17000000
    },
    {
        "option_id": "parental_control",
        "value_type": "Integer",
        "value": 1
    },
    {
        "option_id": "rewards_cap",
        "value_type": "Integer",
        "value": 40
    },
    {
        "option_id": "voluntary_death",
        "value_type": "Integer",
        "value": 0
    },
    {
        "option_id": "golden_triangle",
        "value_type": "Boolean",
        "value": false
    },
    {
        "option_id": "location_based_service_enable",
        "value_type": "Boolean",
        "value": true
    }
]

The value filed changes type depending on the value_type -- I tried doing this using interface{} in struct, but the problem is when I try to get an int type or when value is an object how to access internal fields like validForVerification etc.. I also tried parsing into map, but it fails.

I have no control on the API - so I have to live with this weird JSON.

User3
  • 2,465
  • 8
  • 41
  • 84
  • 2
    Duplicate. Unmarshal value into a json.RawMessage during the first unmarshaling and switch on value_type to determine what type to use to unmarshal that json.RawMessage into in a second step. – Volker Jan 19 '21 at 09:42
  • Can you link the duplicate question? I will take reference from there.. – User3 Jan 19 '21 at 09:55
  • 2
    https://golang.org/pkg/encoding/json/#example_RawMessage_unmarshal – Peter Jan 19 '21 at 10:19
  • @User3 So I'm supposed to do the search work? – Volker Jan 19 '21 at 11:06
  • Nope if you hadn't marked this as a dupe I wouldn't have asked you! On a lighter note, I can well imagine what a pain you'd be to your team haha! – User3 Jan 19 '21 at 14:59
  • Thanks @Peter, thanks for pointing me a direction :) – User3 Jan 19 '21 at 15:01
  • See question [Is there a way to dynamically unmarshal json base on content?](https://stackoverflow.com/q/58073214/5728991) and other questions linked from there. – Charlie Tumahai Jan 19 '21 at 15:33
  • Thanks @CeriseLimón - I have solved it with the reference from @Peter! – User3 Jan 19 '21 at 17:01

0 Answers0