1

In a JSON response from a server, can the same property have a different type based on the value of another property, or is this an antipattern that should be avoided?

Example:

[
  {
    "value": 1.2,
    "valueType": "Numeric"
  },
  {
    "value": false,
    "valueType": "Boolean"
  }
]
4thex
  • 1,094
  • 1
  • 9
  • 21
  • yes, type can be found without separate property https://stackoverflow.com/questions/39802506/constructor-vs-typeof-to-detect-type-in-javascript – Slai Aug 31 '18 at 17:13
  • Yes, I am not worried about whether I can detect the type. I am worried that a consumer might have a hard time decoding the response. – 4thex Aug 31 '18 at 20:43
  • then the safer option is to have the same string type. Seems opinion based, because I am guessing static typed languages (like C#) users might prefer to deserialize to the same string type, and that would also give them more control of how numbers are parsed, but others (like me) might prefer not having to deal with that and the extra parsing code – Slai Aug 31 '18 at 21:21

2 Answers2

2

I'm unsure of the use case of wanting multiple different datatypes to be returned from a single JSON property. The most dynamic property, if you feel this is necessary, would be a String with a series of try/catches in your middle-tier logic to parse out the result you were hoping for. Otherwise, I would try and perhaps break the field that you're trying to capture into multiple meaningful fields to more accurately capture the data you're looking for.

Anthos
  • 111
  • 2
2

The way to do that is usually to encode the value as a string. And then whoever receives the value can parse it accordingly based on the valueType. It is better if the type is known ahead of time, but sometimes you have to work with this situation.

[
  {
    "value": "1.2",
    "valueType": "Numeric"
  },
  {
    "value": "false",
    "valueType": "Boolean"
  }
]
Magdrop
  • 568
  • 3
  • 13