jsonjsonschemajsonparser

JSON Schema - how to get the same result from different data types


I have stumbled here upon several answers regarding handling multiple types of data in JSON, but none of them helps me in my concrete case. I am a beginner in JSON, so any help is highly appreciated.

Namely, I can get the same data from HTTP request as an object in these two variations:

First case:

"cac:PayeeFinancialAccount": {
    "cbc:ID": {
        "@schemeID": "IBAN",
        "#text": "220-115524-04"
    }

Second case:

    "cac:PayeeFinancialAccount": {
    "cbc:ID": "220-115524-04"
    }

Is there a way to get the same form of result from parsing this JSON in any of those cases, a plain string I can grab later in my app, just "220-115524-04" that I can call via like ['cac:PayeeFinancialAccount']?['cbc:ID'] (ignoring other properties)?

Thanks everybody in advance.

I have tried employing "oneOf" from some other answers here, with some success, but couldn't manage to get the same output for both cases.


Solution

  • without seeing your JSON Schema, it's hard to determine what you have tried or how the schema was written.

    This should work to validate both of your instances.

    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "type": "object",
      "properties": {
        "cac:PayeeFinancialAccount": {
          "type": "object",
          "properties": {
            "cbc:ID": {
              "oneOf": [
                {
                  "type": "object",
                  "additionalProperties": false,
                  "properties": {
                    "@schemeID": {
                      "type": "string"
                    },
                    "#text": {
                      "type": "string"
                    }
                  }
                },
                {
                  "type": "string"
                }
              ]
            }
          }
        }
      }
    }