Rafael
Rafael

Reputation: 153

How to use one or another variable to json marshal with same json tag

Supose I have the structure:

type foo struct {
    Name        string        `json:"name"`
    AgeYears    int           `json:"age" rlp:"optional"`
    AgeTimestamp time.Duration `json:"age" rlp:"optional"`
}

I want to return the var AgeYears OR AgeTimestamp into the json tag "age":

if isTimestamp{
    return &foo{
        Name:"Per",
        AgeTimestamp: 1342342554,
    } 
}else{
    return &foo{
        Name:"Per",
        AgeYear:30,
    } 
}

In the first case (isTimestamp==true) I'd like to receive:

{
    "name": "Per",
    "age": 1342342554
}

and in the second:

{
    "name": "Per",
    "age": 30
}

Is it possible in golang? How?

Upvotes: -3

Views: 92

Answers (1)

Volker
Volker

Reputation: 42448

How to use one or another variable to json marshal with same json tag [?]

This simply isn't possible with encoding/json.

You either have to look for a JSON library that supports this, write your own, use different stucts with different tags or use e.g. a map.

Upvotes: 1

Related Questions