Política XMLtoJSON

Esta página se aplica a Apigee y Apigee Hybrid.

Consulta la documentación de Apigee Edge.

Icono de política

Qué

Esta política convierte los mensajes del formato de lenguaje de marcado extensible (XML) a la notación de objetos JavaScript (JSON), lo que te ofrece varias opciones para controlar cómo se convierten los mensajes.

Si el objetivo es convertir una respuesta con formato XML en una respuesta con formato JSON, la política se adjuntaría a un flujo de respuesta (por ejemplo, Response/ProxyEndpoint/PostFlow).

Esta política es una política estándar y se puede implementar en cualquier tipo de entorno. Para obtener información sobre los tipos de políticas y la disponibilidad de cada tipo de entorno, consulta Tipos de políticas.

Información

En un escenario de mediación habitual, una política de JSON a XML en el flujo de solicitudes entrantes suele combinarse con una política de XML a JSON en el flujo de respuestas salientes. Al combinar las políticas de esta forma, se puede exponer una API JSON para los servicios de backend que solo admiten XML de forma nativa.

En los casos en los que las APIs se usan en diversas aplicaciones cliente que pueden requerir JSON o XML, el formato de respuesta se puede definir de forma dinámica configurando políticas de JSON a XML y de XML a JSON para que se ejecuten de forma condicional. Consulta Variables y condiciones de flujo para ver una implementación de este caso.


Ejemplos

Para obtener información detallada sobre la conversión entre JSON y XML, consulta este artículo.

Convertir una respuesta

<XMLToJSON name="ConvertToJSON">
  <Options>
  </Options>
  <OutputVariable>response</OutputVariable>
  <Source>response</Source>
</XMLToJSON>

Esta configuración, que es la mínima necesaria para convertir XML a JSON, toma como origen un mensaje de respuesta con formato XML y, a continuación, crea un mensaje con formato JSON que se rellena en response OutputVariable. Apigee usa automáticamente el contenido de esta variable como mensaje para el siguiente paso de procesamiento.


Referencia de elemento

A continuación, se indican los elementos y atributos que puedes configurar en esta política.

<XMLToJSON async="false" continueOnError="false" enabled="true" name="XML-to-JSON-1">
    <DisplayName>XML to JSON 1</DisplayName>
    <Source>response</Source>
    <OutputVariable>response</OutputVariable>
    <Options>
        <RecognizeNumber>true</RecognizeNumber>
        <RecognizeBoolean>true</RecognizeBoolean>
        <RecognizeNull>true</RecognizeNull>
        <NullValue>NULL</NullValue>
        <NamespaceBlockName>#namespaces</NamespaceBlockName>
        <DefaultNamespaceNodeName>&</DefaultNamespaceNodeName>
        <NamespaceSeparator>***</NamespaceSeparator>
        <TextAlwaysAsProperty>true</TextAlwaysAsProperty>
        <TextNodeName>TEXT</TextNodeName>
        <AttributeBlockName>FOO_BLOCK</AttributeBlockName>
        <AttributePrefix>BAR_</AttributePrefix>
        <OutputPrefix>PREFIX_</OutputPrefix>
        <OutputSuffix>_SUFFIX</OutputSuffix>
        <StripLevels>2</StripLevels>
        <TreatAsArray>
            <Path unwrap="true">teachers/teacher/studentnames/name</Path>
        </TreatAsArray>
    </Options>
    <!-- Use Options or Format, not both -->
    <Format>yahoo</Format>
</XMLToJSON>

Atributos de <XMLtoJSON>

<XMLtoJSON async="false" continueOnError="false" enabled="true" name="XML-to-JSON-1">

The following table describes attributes that are common to all policy parent elements:

Attribute Description Default Presence
name

The internal name of the policy. The value of the name attribute can contain letters, numbers, spaces, hyphens, underscores, and periods. This value cannot exceed 255 characters.

Optionally, use the <DisplayName> element to label the policy in the management UI proxy editor with a different, natural-language name.

N/A Required
continueOnError

Set to false to return an error when a policy fails. This is expected behavior for most policies.

Set to true to have flow execution continue even after a policy fails. See also:

false Optional
enabled

Set to true to enforce the policy.

Set to false to turn off the policy. The policy will not be enforced even if it remains attached to a flow.

true Optional
async

This attribute is deprecated.

false Deprecated

<DisplayName> element

Use in addition to the name attribute to label the policy in the management UI proxy editor with a different, natural-language name.

<DisplayName>Policy Display Name</DisplayName>
Default

N/A

If you omit this element, the value of the policy's name attribute is used.

Presence Optional
Type String

Elemento <Source>

La variable que especifica el mensaje XML que quieres convertir a JSON.

El encabezado Content-type HTTP del mensaje de origen debe tener el valor application/xml. De lo contrario, no se aplicará la política.

Si no se define <Source>, se trata como message, que se resuelve como request cuando la política se adjunta a un flujo de solicitudes o response cuando la política se adjunta a un flujo de respuestas.

Si no se puede resolver la variable de origen o se resuelve en un tipo que no es de mensaje, la política genera un error.

<Source>response</Source>
Predeterminado El valor del elemento Source
Presencia Opcional
Tipo Mensaje

Elemento <OutputVariable>

Especifica dónde se almacenará el resultado de la conversión del formato XML a JSON. Normalmente, este elemento no se incluye en la configuración de la política.

Apigee analiza la carga útil del mensaje XML especificado en Source, la convierte en JSON, almacena el resultado en la carga útil de OutputVariable y asigna el valor application/json al encabezado Content-type HTTP del mensaje OutputVariable.

Si no se especifica OutputVariable, se usa el valor de Source de forma predeterminada. Por ejemplo, si source es response, OutputVariable tendrá el valor predeterminado response.

<OutputVariable>response</OutputVariable>
Predeterminado El mensaje especificado en Source
Presencia Opcional
Tipo Mensaje

<Opciones>

Las opciones te permiten controlar la conversión de XML a JSON. Usa el grupo <Options>, que te permite añadir ajustes de conversión específicos, o el elemento <Format>, que te permite hacer referencia a una plantilla de opciones predefinidas. No puedes usar <Options> y <Format> al mismo tiempo.

<Options> es obligatorio si no se usa <Format>.

Elemento <RecognizeNumber>

Si es true, los campos de número de la carga útil XML conservan su formato original.

<RecognizeNumber>true</RecognizeNumber>

Veamos el siguiente ejemplo de XML:

<a>
  <b>100</b>
  <c>value</c>
</a>

Si RecognizeNumber es true, la política lo convierte en lo siguiente:

{
    "a": {
        "b": 100,
        "c": "value"
    }
}

Si RecognizeNumber es false, la política lo convierte en lo siguiente:

{
  "a": {
    "b": "100",
    "c": "value"
  }
}
Predeterminado falso
Presencia Opcional
Tipo Booleano

Elemento <RecognizeBoolean>

Permite que la conversión mantenga los valores booleanos true/false en lugar de convertir los valores en cadenas.

<RecognizeBoolean>true</RecognizeBoolean>

En el siguiente ejemplo de XML:

<a>
  <b>true</b>
  <c>value</c>
</a>

Si RecognizeBoolean es true, la política lo convierte en lo siguiente:

{
    "a": {
        "b": true,
        "c": "value"
    }
}

Si RecognizeBoolean es false, la política lo convierte en lo siguiente:

{
    "a": {
        "b": "true",
        "c": "value"
    }
}
Predeterminado falso
Presencia Opcional
Tipo Booleano

Elemento <RecognizeNull>

Permite convertir valores vacíos en valores nulos.

<RecognizeNull>true</RecognizeNull>

Para el siguiente XML:

<a>
  <b></b>
  <c>value</c>
</a>

Si RecognizeNull es true y no hay ninguna opción NullValue, este XML se convierte en lo siguiente:

{
  "a": {
    "b": null,
    "c": "value"
  }
}

Si RecognizeNull es false, este XML se convierte en lo siguiente:

{
  "a": {
    "b": {},
    "c": "value"
  }
}
Predeterminado falso
Presencia Opcional
Tipo Booleano

Elemento <NullValue>

Indica el valor al que se deben convertir los valores nulos reconocidos en el mensaje de origen. De forma predeterminada, el valor es null. Esta opción solo tiene efecto si RecognizeNull es true.

<NullValue>not-present</NullValue>

Para el siguiente XML:

<a>
  <b></b>
  <c>value</c>
</a>

Si RecognizeNull es true y no se especifica NullValue, este XML se convierte en lo siguiente:

{
  "a": {
    "b": null,
    "c": "value"
  }
}

Si RecognizeNull es true y NullValue es not-present, este XML se convierte en lo siguiente:

{
  "a": {
    "b": "not-present",
    "c": "value"
  }
}
Predeterminado null
Presencia Opcional
Tipo Cadena

Opciones de espacio de nombres

De forma predeterminada, esta política omite los espacios de nombres XML en el JSON generado. Para especificar que los espacios de nombres del documento XML se traduzcan al JSON generado, utilice estos elementos juntos.

<NamespaceBlockName>#namespaces</NamespaceBlockName>
<DefaultNamespaceNodeName>&</DefaultNamespaceNodeName>
<NamespaceSeparator>***</NamespaceSeparator>

Veamos el siguiente ejemplo de XML:

<a xmlns="http://ns.com" xmlns:ns1="http://ns1.com">
  <ns1:b>value</ns1:b>
</a>

Si no se especifica NamespaceSeparator, se genera la siguiente estructura JSON:

{
    "a": {
        "b": "value"
    }
}

Si los elementos NamespaceBlockName, DefaultNamespaceNodeName y NamespaceSeparator se especifican como #namespaces, & y ***, respectivamente, se generará la siguiente estructura JSON:

{
    "a": {
        "#namespaces": {
            "&": "http://ns.com",
            "ns1": "http://ns1.com"
        },
        "ns1***b": "value"
    }
}
Predeterminado Ninguno Si no se especifica <NamespaceBlockName>, la política generará un JSON de salida que no haga referencia a ningún espacio de nombres XML, independientemente de si el mensaje de origen hacía referencia a espacios de nombres.
Presencia Opcional
Sin embargo, si especifica <NamespaceBlockName>, también debe especificar los otros dos elementos.
Tipo Cadenas

Opciones de texto

Usa estos elementos juntos.

      <TextAlwaysAsProperty>true|false</TextAlwaysAsProperty>
      <TextNodeName>TEXT</TextNodeName>

Cuando la política encuentra un elemento XML que contiene solo un nodo de texto como elemento secundario, la política traduce el contenido de texto de ese elemento XML en una propiedad del hash JSON.

Cuando la política detecta un elemento XML que contiene varios elementos secundarios de contenido mixto, estas opciones le permiten controlar el JSON de salida de cualquier nodo de texto secundario.

Por ejemplo, considere esta configuración de política:

<XMLToJSON name='XMLToJSON-1'>
  <Options>
    <TextAlwaysAsProperty>???</TextAlwaysAsProperty>
    <TextNodeName>#text</TextNodeName>
  </Options>
</XMLToJSON>

En función de si TextAlwaysAsProperty es true o false, la política generará los siguientes resultados para las entradas XML proporcionadas:

Entrada XML Salida JSON
cuando TextAlwaysAsProperty es false cuando TextAlwaysAsProperty es true
<a>value1</a>
{
  "a": "value1"
}
{
  "a": {
    "#text": "value1"
  }
}
<a>value1
  <b>value2</b>
</a>
{
  "a": {
    "#text": "value1\n",
    "b": "value2"
  }
}
{
  "a": {
    "#text": "value1\n",
    "b": {
      "#text": "value2"
    }
  }
}
Predeterminado <TextAlwaysAsProperty>: false
<TextNodeName>: (cadena vacía)
Presencia Opcional
Tipo <TextAlwaysAsProperty>: booleano
<TextNodeName>: cadena

Opciones de atributo

Estos elementos, en conjunto, te permiten agrupar valores de atributos en un bloque JSON y añadir prefijos a los nombres de los atributos.

<AttributeBlockName>FOO_BLOCK</AttributeBlockName>
<AttributePrefix>BAR_</AttributePrefix>

Veamos el siguiente ejemplo de XML:

<a attrib1="value1" attrib2="value2"/>

Si se especifican ambos atributos (AttributeBlockName y AttributePrefix) tal como se definen en el ejemplo de XML a JSON, se genera la siguiente estructura JSON:

{
  "a": {
    "FOO_BLOCK": {
      "BAR_attrib1": "value1",
      "BAR_attrib2": "value2"
    }
  }
}

Si solo se especifica AttributeBlockName, se genera la siguiente estructura JSON:

{
    "a": {
        "FOO_BLOCK": {
            "attrib1": "value1",
            "attrib2": "value2"
        }
    }
}

Si solo se especifica AttributePrefix, se genera la siguiente estructura JSON:

{
    "a": {
        "BAR_attrib1": "value1",
        "BAR_attrib2": "value2"
    }
}

Si no se especifica ninguno de los dos, se genera la siguiente estructura JSON:

{
    "a": {
        "attrib1": "value1",
        "attrib2": "value2"
    }
}
Predeterminado Ninguna.
Presencia Opcional
Tipo Cadena

Elementos <OutputPrefix> y <OutputSuffix>

Usa estos elementos juntos para aplicar un prefijo o un sufijo al JSON generado.

<OutputPrefix>PREFIX_</OutputPrefix>
<OutputSuffix>_SUFFIX</OutputSuffix>

Veamos el siguiente ejemplo de XML:

<a>value</a>

Supongamos que la configuración de la política es la siguiente:

<XMLToJSON name='XMLToJSON-4'>
  <Options>
    <OutputPrefix>{ "result": </OutputPrefix>
    <OutputSuffix>}</OutputSuffix>
  </Options>
</XMLToJSON>

Se genera la siguiente estructura JSON:

{
  "result": {
    "a": "value"
  }
}

Puedes omitir OutputPrefix o OutputSuffix, o ambos.

Con estos elementos, se puede generar un JSON no válido. Por ejemplo, si usas esta configuración de política:

<XMLToJSON name='XMLToJSON-4'>
  <Options>
    <OutputPrefix>PREFIX_</OutputPrefix>
  </Options>
</XMLToJSON>

La política genera lo siguiente, que no es un JSON válido:

PREFIX_{
  "a" : "value"
}

Si en la configuración no se especifica ni OutputPrefix ni OutputSuffix, la política genera la siguiente estructura JSON:

{
  "a": "value"
}
Predeterminado Consulta los ejemplos de arriba.
Presencia Opcional
Tipo Cadena

Elemento <StripLevels>

<Options>
    <StripLevels>4</StripLevels>
</Options>

A veces, las cargas útiles XML, como SOAP, tienen muchos niveles superiores que no quieres incluir en el JSON convertido. A continuación se muestra un ejemplo de respuesta SOAP que contiene muchos niveles:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/Schemata-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
      <GetCityWeatherByZIPResponse xmlns="http://ws.cdyne.com/WeatherWS/">
          <GetCityWeatherByZIPResult>
              <State>CO</State>
              <City>Denver</City>
              <Description>Sunny</Description>
              <Temperature>62</Temperature>
          </GetCityWeatherByZIPResult>
      </GetCityWeatherByZIPResponse>
  </soap:Body>
</soap:Envelope>

Hay 4 niveles antes de llegar a los niveles Estado, Ciudad, Descripción y Temperatura. Sin usar <StripLevels>, la respuesta JSON convertida tendría este aspecto:

{
   "Envelope" : {
      "Body" : {
         "GetCityWeatherByZIPResponse" : {
            "GetCityWeatherByZIPResult" : {
               "State" : "CO",
               "City" : "Denver",
               "Description" : "Sunny",
               "Temperature" : "62"
            }
         }
      }
   }
}

Si quieres eliminar esos cuatro primeros niveles de la respuesta JSON, debes definir <StripLevels>4</StripLevels>, lo que te dará el siguiente JSON:

{
  "State" : "CO",
  "City" : "Denver",
  "Description" : "Sunny",
  "Temperature" : "62"
}

Puedes eliminar niveles hasta el primer elemento que contenga varios elementos secundarios. ¿Qué significa eso? Veamos un ejemplo de JSON más complejo:

{
   "Envelope" : {
      "Body" : {
         "GetCityForecastByZIPResponse" : {
            "GetCityForecastByZIPResult" : {
               "ResponseText" : "City Found",
               "ForecastResult" : {
                  "Forecast" : [
                     {
                        "ProbabilityOfPrecipiation" : {
                           "Nighttime" : "00",
                           "Daytime" : 10
                        }  ...

El nivel 3 de este ejemplo es GetCityForecastByZIPResponse, que solo tiene un elemento secundario. Por lo tanto, si usara <StripLevels>3</StripLevels> (quitar los tres primeros niveles), el JSON tendría este aspecto:

{
   "GetCityForecastByZIPResult" : {
      "ResponseText" : "City Found",
      "ForecastResult" : {
         "Forecast" : [
            {
               "ProbabilityOfPrecipiation" : {
                  "Nighttime" : "00",
                  "Daytime" : 10
               }  ...

Ten en cuenta que GetCityForecastByZIPResult tiene varios elementos secundarios. Como es el primer elemento que contiene varios elementos secundarios, puedes eliminar este último nivel con <StripLevels>4</StripLevels>, lo que te dará el siguiente JSON:

{
   "ResponseText" : "City Found",
   "ForecastResult" : {
      "Forecast" : [
         {
            "ProbabilityOfPrecipiation" : {
               "Nighttime" : "00",
               "Daytime" : 10
            }  ...

Como el nivel 4 es el primero que contiene varios elementos secundarios, no puedes eliminar ningún nivel inferior. Si ajustas el nivel de la tira a 5, 6, 7, etc., seguirás recibiendo la respuesta anterior.

Predeterminado 0 (sin eliminación de niveles)
Presencia Opcional
Tipo Entero

Elemento <TreatAsArray>/<Path>

<Options>
    <TreatAsArray>
        <Path unwrap="true">teachers/teacher/studentnames/name</Path>
    </TreatAsArray>
</Options>

Esta combinación de elementos le permite asegurarse de que los valores de un documento XML siempre se traducen a una matriz JSON. Esto puede ser útil cuando el número de elementos secundarios varía en diferentes cargas útiles. El comportamiento predeterminado de Apigee es convertir varios elementos secundarios con el mismo nombre en una matriz JSON y los elementos secundarios únicos en un primitivo JSON. La opción TreatAsArray le permite asegurarse de que los elementos secundarios se traduzcan siempre a una matriz JSON.

Si usas TreatAsArray, puedes mejorar la estructura del código posterior que gestiona la salida, ya que los datos de la matriz se devuelven de la misma forma cada vez. Por ejemplo, al evaluar un JSONPath de $.teachers.teacher.studentnames.name[0], se devolverá el valor del nombre de forma coherente, independientemente de si el XML original contenía uno o más elementos name.

Vamos a volver a ver el comportamiento predeterminado de XML a JSON y, después, vamos a descubrir cómo controlar el resultado con <TreatAsArray>/<Path>.

Cuando un documento XML contiene un elemento con varias apariciones (lo que puede ocurrir cuando el esquema XML especifica maxOccurs='unbounded' para el elemento), la política de XML a JSON coloca automáticamente esos valores en una matriz. Por ejemplo, el siguiente bloque XML

<teacher>
    <name>teacherA</name>
    <studentnames>
        <name>student1</name>
        <name>student2</name>
    </studentnames>
</teacher>

...se convierte automáticamente en el siguiente JSON sin necesidad de configurar ninguna política especial:

{
  "teachers" : {
    "teacher" : {
      "name" : "teacherA",
      "studentnames" : {
        "name" : [
          "student1",
          "student2"
        ]
      }
    }
  }
}

Observa que los dos nombres de los alumnos están incluidos en una matriz.

Sin embargo, si solo aparece un alumno en el documento XML, la política de XML a JSON tratará automáticamente el valor como una sola cadena, no como una matriz de cadenas, como se muestra en el siguiente ejemplo:

{
  "teachers" : {
    "teacher" : {
      "name" : "teacherA",
      "studentnames" : {
        "name" : "student1"
      }
    }
  }
}

En los ejemplos anteriores, los datos similares se han convertido de forma diferente: una vez en una matriz y otra en una sola cadena. El elemento <TreatAsArray>/<Path> te permite controlar la salida para asegurarte de que los nombres de los alumnos se conviertan siempre en un array, aunque solo haya un valor. Para configurarlo, debe identificar la ruta al elemento cuyos valores quiera convertir en una matriz, de la siguiente manera:

<Options>
    <TreatAsArray>
        <Path>teachers/teacher/studentnames/name</Path>
    </TreatAsArray>
</Options>

La configuración anterior generaría el JSON de la siguiente manera:

{
  "teachers" : {
    "teacher" : {
      "name" : "teacherA",
      "studentnames" : {
        "name" : ["student1"]
      }
    }
  }
}

Observa que student1 ahora está en una matriz. Ahora, independientemente de si hay uno o varios alumnos, puedes recuperarlos de una matriz JSON en tu código mediante el siguiente JSONPath: $.teachers.teacher.studentnames.name[0]

El elemento <Path> también tiene un atributo unwrap, que se explica en la siguiente sección.

Predeterminado N/A
Presencia Opcional
Tipo Cadena

Atributos

 <Options>
    <TreatAsArray>
        <Path unwrap="true">teachers/teacher/studentnames/name</Path>
    </TreatAsArray>
</Options>
Atributo Descripción Presencia Tipo
desenvolver

Valor predeterminado: false

Quita el elemento del resultado JSON. Úsalo para simplificar o aplanar ("desenvolver") el JSON, lo que también acorta el JSONPath necesario para recuperar valores. Por ejemplo, en lugar de $.teachers.teacher.studentnames.name[*], puedes acoplar el JSON y usar $.teachers.studentnames[*].

Aquí tienes un ejemplo en JSON:

{
  "teachers" : {
      "teacher" : {
          "name" : "teacherA",
          "studentnames" : {
              "name" : [
                 "student1",
                 "student2"
              ]}...

En este ejemplo, podría decirse que el elemento teacher y el elemento studentnames name no son necesarios. Por lo tanto, puedes quitar o envolver los elementos. Para configurar el elemento <Path> de esta forma, sigue estos pasos:

<TreatAsArray>
    <Path unwrap="true">teachers/teacher</Path>
    <Path unwrap="true">teachers/teacher/studentnames/name</Path>
</TreatAsArray>

El atributo unwrap se define como true y se proporcionan las rutas a los elementos que se van a desenvolver. La salida JSON tendrá este aspecto:

{
  "teachers" : [{
      "name" : "teacherA",
      "studentnames" : ["student1","student2"]
      }]...

Ten en cuenta que, como el elemento <Path> está en el elemento <TreatAsArray>, ambos elementos de la ruta se tratarán como matrices en el resultado JSON.

Opcional Booleano

Para ver más ejemplos y una guía de la función, consulta este artículo de la comunidad de Google Cloud.

<Format>

El formato te permite controlar la conversión de XML a JSON. Introduce el nombre de una plantilla predefinida que contenga una combinación específica de elementos Options descritos en este tema. Entre los formatos predefinidos se incluyen xml.com, yahoo, google y badgerFish.

Usa el elemento <Format> o el grupo <Options>. No puedes usar <Format> y <Options> al mismo tiempo.

A continuación, se muestran las definiciones de formato de cada plantilla predefinida.

xml.com

<RecognizeNull>true</RecognizeNull>
<TextNodeName>#text</TextNodeName>
<AttributePrefix>@</AttributePrefix>

yahoo

<RecognizeNumber>true</RecognizeNumber>
<TextNodeName>content</TextNodeName>

google

<TextNodeName>$t</TextNodeName>
<NamespaceSeparator>$</NamespaceSeparator>
<TextAlwaysAsProperty>true</TextAlwaysAsProperty>

badgerFish

<TextNodeName>$</TextNodeName>
<TextAlwaysAsProperty>true</TextAlwaysAsProperty>
<AttributePrefix>@</AttributePrefix>
<NamespaceSeparator>:</NamespaceSeparator>
<NamespaceBlockName>@xmlns</NamespaceBlockName>
<DefaultNamespaceNodeName>$</DefaultNamespaceNodeName>

Sintaxis del elemento:

<Format>yahoo</Format>
Predeterminado (ninguna)
Valores válidos Uno de los siguientes:
xml.com, yahoo, google o badgerFish
Presencia Es opcional, pero obligatorio si no se usa <Options>.
Tipo Cadena

Esquemas


Referencia de errores

This section describes the fault codes and error messages that are returned and fault variables that are set by Apigee when this policy triggers an error. This information is important to know if you are developing fault rules to handle faults. To learn more, see What you need to know about policy errors and Handling faults.

Runtime errors

These errors can occur when the policy executes.

Fault code HTTP status Cause Fix
steps.xmltojson.ExecutionFailed ExecutionFailed This error occurs when the input payload (XML) is empty or the input XML is invalid or malformed.
steps.xmltojson.InCompatibleTypes ExecutionFailed This error occurs if the type of the variable defined in the <Source> element and the <OutputVariable> element are not the same. It is mandatory that the type of the variables contained within the <Source> element and the <OutputVariable> element matches.
steps.xmltojson.InvalidSourceType ExecutionFailed This error occurs if the type of the variable used to define the <Source> element is invalid.The valid types of variable are message and string.
steps.xmltojson.OutputVariableIsNotAvailable ExecutionFailed This error occurs if the variable specified in the <Source> element of the XML to JSON policy is of type string and the <OutputVariable> element is not defined. The <OutputVariable> element is mandatory when the variable defined in the <Source> element is of type string.
steps.xmltojson.SourceUnavailable ExecutionFailed This error occurs if the message variable specified in the <Source> element of the XML to JSON policy is either:
  • Out of scope (not available in the specific flow where the policy is being executed) or
  • Can't be resolved (is not defined)

Deployment errors

These errors can occur when you deploy a proxy containing this policy.

Error name Cause Fix
EitherOptionOrFormat If one of the elements <Options> or <Format> is not declared in the XML to JSON Policy, then the deployment of the API proxy fails.
UnknownFormat If the <Format> element within the XML to JSON policy has an unknown format defined, then the deployment of the API proxy fails. Predefined formats include: xml.com, yahoo, google, and badgerFish.

Fault variables

These variables are set when a runtime error occurs. For more information, see What you need to know about policy errors.

Variables Where Example
fault.name="fault_name" fault_name is the name of the fault, as listed in the Runtime errors table above. The fault name is the last part of the fault code. fault.name = "SourceUnavailable"
xmltojson.policy_name.failed policy_name is the user-specified name of the policy that threw the fault. xmltojson.XMLtoJSON-1.failed = true

Example error response

{
  "fault": {
    "faultstring": "XMLToJSON[XMLtoJSON-1]: Source xyz is not available",
    "detail": {
      "errorcode": "steps.xml2json.SourceUnavailable"
    }
  }
}

Example fault rule

<faultrule name="VariableOfNonMsgType"></faultrule><FaultRule name="XML to JSON Faults">
    <Step>
        <Name>AM-SourceUnavailableMessage</Name>
        <Condition>(fault.name Matches "SourceUnavailable") </Condition>
    </Step>
    <Step>
        <Name>AM-BadXML</Name>
        <Condition>(fault.name = "ExecutionFailed")</Condition>
    </Step>
    <Condition>(xmltojson.XMLtoJSON-1.failed = true) </Condition>
</FaultRule>

Temas relacionados

De JSON a XML: política JSONtoXML