Question
· May 16, 2023

The best kept secret to remove a key in your JSON response - unlock the answer!

Good morning:


Thank you very much for reading the doubt and above all thank you very much for answering.

 

Given the following use case:

If we have a Destination Service that through a HTTP GET by REST gives us a certain JSON response, where it should be noted that it is a list of objects where each object in the list does NOT have a key:

[
    {
        "codigo": "5128",
        "descripcion": "LAS ENFERMERAS FRENTE A LOS PROBLEMAS DE SALUD MENTAL",
        "programa": "Probabilidad de contagio ante un accidente hemático.",
        "admitido": 1,
        "desdefecha": "26/10/2022",
        "hastafecha": "26/10/2029",
        "cursohorario": [
            {
                "aula": "AULA 1",
                "desdefecha": "2022/12/26",
                "hastafecha": "2022/12/26",
                "desdehora": "16:00:00",
                "hastahora": "20:30:00"
            },
            {
                "aula": "AULA 2",
                "desdefecha": "27/10/2022",
                "hastafecha": "27/12/2022",
                "desdehora": "10:00:00",
                "hastahora": "12:45:00"
            }
        ],
        "error": null
    },
    {
        "codigo": "5129",
        "descripcion": "HISTORIA DE SALUD ELECTRONICA DRAGO-AP",
        "programa": "XXXX",
        "admitido": 0,
        "desdefecha": "15/01/2022",
        "hastafecha": "15/01/2029",
        "cursohorario": [
            {
                "aula": "AULA MAGNA",
                "desdefecha": "15/01/2022",
                "hastafecha": "15/01/2022",
                "desdehora": "16:00:00",
                "hastahora": "20:30:00"
            }
        ],
        "error": null
    }
]

 

Currently we have integrated us and the Destination Service, by making the HealtShare the ESB interoperability intermediary, and when returning the response from Destination System passing through the ESB to Origin System we see a weird bizarre spurious key called "cursos":

{
    "cursos": [
        {
            "codigo": 5128,
            "descripcion": "LAS ENFERMERAS FRENTE A LOS PROBLEMAS DE SALUD MENTAL",
            "programa": "Probabilidad de contagio ante un accidente hemático.",
            "admitido": 1,
            "desdefecha": "26/10/2022",
            "hastafecha": "26/10/2029",
            "cursohorario": [
                {
                    "aula": "AULA 1",
                    "desdefecha": "2022/12/26",
                    "hastafecha": "2022/12/26",
                    "desdehora": "16:00:00",
                    "hastahora": "20:30:00"
                },
                {
                    "aula": "AULA 2",
                    "desdefecha": "27/10/2022",
                    "hastafecha": "27/12/2022",
                    "desdehora": "10:00:00",
                    "hastahora": "12:45:00"
                }
            ],
            "error": null
        },
        {
            "codigo": 5129,
            "descripcion": "HISTORIA DE SALUD ELECTRONICA DRAGO-AP",
            "programa": "XXXX",
            "admitido": 0,
            "desdefecha": "15/01/2022",
            "hastafecha": "15/01/2029",
            "cursohorario": [
                {
                    "aula": "AULA MAGNA",
                    "desdefecha": "15/01/2022",
                    "hastafecha": "15/01/2022",
                    "desdehora": "16:00:00",
                    "hastahora": "20:30:00"
                }
            ],
            "error": null
        }
    ]
}

Is there any way to remove that "cursos" key?

I appreciate your help and I appreciate your response and thank you for explaining the solution.

 

We share our code with you to give context.

Service method to read input, and also converts XML from Process' response to JSON because Origin System needs it to be JSON:

Method getCursosAdmitidos(pInput As %Stream.Object, Output pOutput As %Stream.Object) As %Status
{
	Set pOutput=##class(%GlobalBinaryStream).%New()
	set claseAux = ##class(%ZEN.Auxiliary.jsonProvider).%New()
	
	//Necesitamos sacar la cabecera "idUserLogueado" de la peticion REST
	;set idUserLogueado = pInput.GetAttribute("idUserLogueado")
	set idUserLogueado = pInput.GetAttribute("iduserlogueado")
	$$$LOGINFO("idUserLogueado: "_idUserLogueado)	
	
	set objetoEntrada = ##class(Mensajes.Request.miFormacion.GetCursosAdmitidosRequest).%New()
	set objetoEntrada.idUserLogueado = idUserLogueado
	$$$LOGINFO("objetoEntrada.idUserLogueado: "_objetoEntrada.idUserLogueado)
	
	//Sacamos el body
	;set body = pInput.Read()
	//Lo convertimos a Mensaje
	;set tSC= claseAux.%ConvertJSONToObject(.body,"Mensajes.Request.miFormacion.GetCursosAdmitidosRequest",.objetoEntrada,1)
	//Enviamos al Proceso
	set tSC = ..SendRequestSync("miFormacionv01r00",objetoEntrada,.objetoSalida)

	//Convertimos el OBJETO devuelto por el Proceso en JSON
	set tSC = claseAux.%WriteJSONStreamFromObject(.pOutput,.objetoSalida,,,,"aeloqtuw")
	
	//Enviamos el JSON con cabeceras
	Do:$$$ISOK(tSC) pOutput.SetAttribute("Content-Type","application/json")
	do pOutput.SetAttribute("Access-Control-Allow-Origin","*")
	do pOutput.SetAttribute("Access-Control-Allow-Credentials","true")
	do pOutput.SetAttribute("Access-Control-Allow-Methods","GET")
    do pOutput.SetAttribute("Access-Control-Allow-Headers","request,Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers")
	Quit tSC
}

Operation to send the GET and to read the JSON to convert it to XML:

Method GetCursosAdmitidos(pRequest As Mensajes.Request.miFormacion.GetCursosAdmitidosRequest, pResponse As Mensajes.Response.miFormacion.GetCursosAdmitidosResponse) As %Library.Status
{
	//Creamos Request y Response HTTP
	Set httpRequest=##class(%Net.HttpRequest).%New()
	set tResponse  = ##class(%Net.HttpResponse).%New()

	// Se obtiene la URL de la configurada en la Producción
	set URL		= ..Adapter.URL_"formacion/getcursosadmitidos"
	$$$LOGINFO("URL: "_URL)
	
	set httpRequest.ContentType = "application/json"
	do httpRequest.SetHeader("idUserLogueado",pRequest.idUserLogueado)	
	set idUserLogueado =httpRequest.GetHeader("idUserLogueado")
	$$$LOGINFO("Enviamos en la cabecera, idUserLogueado: "_idUserLogueado)

	//Enviamos al sistema externo
	set tSC=httpRequest.Get(URL,0) 
	$$$LOGALERT("tSC: "_$System.Status.GetErrorText(tSC))

	//Lanzamos excepcion si hubo error
	if $$$ISERR(tSC){
			$$$ThrowOnError(tSC)
	}
	
	set tResponse = httpRequest.HttpResponse
	
	set linea = ""
	//Leemos respuesta
	if (tResponse.Data.AtEnd = 0) {
		set linea = linea_tResponse.Data.Read()
	}
	$$$LOGINFO("linea: "_linea)
	
	set pResponse = ##class(Mensajes.Response.miFormacion.GetCursosAdmitidosResponse).%New()
	
	// se transforma el objeto JSON a un objeto local ★
	set claseAux = ##class(%ZEN.Auxiliary.jsonProvider).%New()
	set tSC      = claseAux.%ConvertJSONToObject(.linea,"EsquemasDatos.miFormacion.CursoAdmitido",.cursos,1)
	for i=1:1:cursos.Size{
		set curso               	= ##class(EsquemasDatos.miFormacion.CursoAdmitido).%New()
		set curso.codigo         	= cursos.GetAt(i).codigo
		set curso.descripcion 		= cursos.GetAt(i).descripcion
		set curso.programa 			= cursos.GetAt(i).programa
		set curso.admitido     		= cursos.GetAt(i).admitido
		set curso.desdefecha        = cursos.GetAt(i).desdefecha
		set curso.hastafecha      	= cursos.GetAt(i).hastafecha
		for j=1:1:cursos.GetAt(i).cursohorario.Size{
			set cursohorario 			= ##class(EsquemasDatos.miFormacion.CursoHorario).%New()
			set cursohorario.aula 		= cursos.GetAt(i).cursohorario.GetAt(j).aula
			set cursohorario.desdefecha = cursos.GetAt(i).cursohorario.GetAt(j).desdefecha
			set cursohorario.hastafecha = cursos.GetAt(i).cursohorario.GetAt(j).hastafecha
			set cursohorario.desdehora  = cursos.GetAt(i).cursohorario.GetAt(j).desdehora
			set cursohorario.hastahora  = cursos.GetAt(i).cursohorario.GetAt(j).hastahora
			do curso.cursohorario.Insert(cursohorario)
		}
		;set curso.cursohorario      = cursos.GetAt(i).cursohorario
		set curso.error      		= cursos.GetAt(i).error
		do pResponse.cursos.Insert(curso)
	}
	Quit $$$OK
}

 

Response Message being used:

Class Mensajes.Response.miFormacion.GetCursosAdmitidosResponse Extends Ens.Response
{

Property cursos As list Of EsquemasDatos.miFormacion.CursoAdmitido;
Storage Default
{
 ...
}

}

Internal model class to represent each course:

Class EsquemasDatos.miFormacion.CursoAdmitido Extends Ens.Response
{

Property codigo As %String(MAXLEN = "");
Property descripcion As %String(MAXLEN = "");
Property programa As %String(MAXLEN = "");
// Property admitido As %Boolean;
Property admitido As %String(MAXLEN = "");
Property desdefecha As %String(MAXLEN = "");
Property hastafecha As %String(MAXLEN = "");
Property cursohorario As list Of EsquemasDatos.miFormacion.CursoHorario;
Property error As EsquemasDatos.Seguridad.Error;
Storage Default
{
...
<Type>%Storage.Persistent</Type>
}

}

 

I sincerely appreciate your time and attention in reading and, most importantly, providing a helpful response to my inquiry. Thank you so much!

In addition, we have also read:

https://community.intersystems.com/post/json-xml

https://community.intersystems.com/post/how-convert-xml-json

https://docs.intersystems.com/healthconnectlatest/csp/documatic/%25CSP.D...

 

And:

https://community.intersystems.com/post/how-convert-xml-json

https://community.intersystems.com/post/how-convert-xml-json-xmltextread...

 


I am immensely grateful for your valuable time and dedicated effort in carefully considering and providing me with an incredibly insightful response to my query.

Greetings.

Product version: IRIS 2020.1
$ZV: IRIS for UNIX (Red Hat Enterprise Linux for x86-64) 2020.1.1 (Build 408U) Sun Mar 21 2021 22:21:14 EDT
Discussion (3)1
Log in or sign up to continue

Just to rephrase your issue:

  • you expect a JSON array of JSON objects   [{..},{..},{..} ]
  • but you get a JSON object containing that array {"cursos": [{..},{..},{..} ]}
;;  asssumptio input holds the received obj
    set jobj={}.%FromJSON(input) ; convert to obj
    set jarray=jobj.%Get("cursos")   ; content of "cursos" = [..]
    set output=jarray.%ToJSON() ; convert to  string
    

docu: %Library.DynamicObject