FiveTech Support Forums

FiveWin / Harbour / xBase community
Board index FiveWin for Harbour/xHarbour Help with complex JSON
Posts: 708
Joined: Fri Oct 28, 2005 09:53 AM
Help with complex JSON
Posted: Tue Mar 21, 2023 01:20 AM

Hello Everyone,

I have been having a heck of a time trying to decode the JSON code below.

I am trying process the vessel calls in the ReadDataNew function below. When trying to process the data JSON at the end of this message, I get a BOUND error.

I hoping someone can shread some light on the best way to process this data.

Thank you in advance for your assistance!

//-----------------------------------------------------------------------------

static function ReadVessel( hJson )

local aData := {}

local aRow, aCalls, hCall

local d, n, i, j, aDt

local ARRI, DEPA

local cPol, cPolName, cDateTim, dEtd, cEtdTime, cStr

aCalls := hJson[ "vessel" ]

 AADD( aData, { "IMO"     , aCalls["vesselIMONumber"] } )

 AADD( aData, { "VESSEL"  , aCalls["vesselName"] } )

 AADD( aData, { "FLAG"    , aCalls["vesselFlagCode"] } )

 AADD( aData, { "CALLSIGN", aCalls["vesselCallSign"] } )

 AADD( aData, { "VCODE"   , aCalls["carrierVesselCode"] } )

return aData

//-----------------------------------------------------------------------------

static function ReadDataNew( hJson )

local aData := {}

local aRow, aCalls, hCall

local d, n, i, j, aDt

local ARRI, DEPA

local cPol, cPolName, cDateTim, dEtd, cEtdTime

 local lPass := .T., cPass

aCalls := hJson[ "vesselCalls" ]

aEval( aCalls, { |h| hb_HSetCaseMatch( h, .f. ) } )

for n := 1 to Len( aCalls )

        lPass := .T.

        hCall := aCalls[ n ]

  if hCall[ "callSchedules" ][ 1 ][ "transportEventTypeCode" ] == "DEPA"

     DEPA  := 1

     ARRI  := 2

   else

     ARRI  := 1

     DEPA  := 2

  endif



  if n == 1

        cPol     := hCall[ "facility" ][ "UNLocationCode" ]

    cPolName := hCall[ "facility" ][ "portName" ]

    cDateTim := hCall[ "callSchedules" ][ DEPA ][ "classifierDateTime" ]

   else

             if (hCall[ "facility" ][ "UNLocationCode" ] == cPol)

           if ( d := hCall[ "callSchedules" ][ DEPA ][ "classifierDateTime" ] ) > cDateTim

              cDateTim := d

           endif

     else

           if dEtd == nil .AND. (cDateTim <> nil)

              aDt      := ParseDateTime( cDateTim )

              dEtd     := aDt[ 1 ]

              cEtdTime := aDt[ 2 ]

           endif

           aRow  := Array( 12 )

           aRow[ FLD_VESSEL   ]  := hJson[ "vessel" ][ "vesselName" ]

           aRow[ FLD_VOYAGE   ]  := hCall[ "transport" ][ "outboundService" ][ "carrierVoyageNumber" ]

           aRow[ FLD_LLOYDS   ]  := hJson[ "vessel" ][ "vesselIMONumber" ]

           aRow[ FLD_POL      ]  := cPol

           aRow[ FLD_POLNAME  ]  := cPolName

           aRow[ FLD_ETD      ]  := DTOC(dEtd)

           aRow[ FLD_ETDTIME  ]  := cEtdTime

           aRow[ FLD_POUL     ]  := hCall[ "facility" ][ "UNLocationCode" ]

           aRow[ FLD_POULNAME ]  := hCall[ "facility" ][ "portName" ]

           aDt   := ParseDateTime( hCall[ "callSchedules" ][ ARRI ][ "classifierDateTime" ] )

           aRow[ FLD_ETA      ]  := DTOC(aDt[ 1 ])

           aRow[ FLD_ETATIME  ]  := aDt[ 2 ]

                         aRow[ FLD_SERVICE  ]  := hCall[ "transport" ][ "outboundService" ][ "carrierServiceCode" ]

           AAdd( aData, aRow )

     endif

  endif

next

return aData

//-----------------------------------------------------------------------------

static function ParseDateTime( cDateTime )

local dDate, cTime

cTime := SubStr( cDateTime, 12, 8 )

dDate := STOD( StrTran( Left( cDateTime, 10 ), "-", "" ) )

return { dDate, cTime }

/*** JSON below

{"vessel":{"vesselIMONumber":"9332999","carrierVesselCode":"Q4F","vesselName":"MAERSK DENVER","vesselFlagCode":"US","vesselCallSign":"WMDQ"},"vesselCalls":[{"callSchedules":[{"transportEventTypeCode":"ARRI","eventClassifierCode":"EST","classifierDateTime":"2023-03-21T20:30:00"},{"transportEventTypeCode":"DEPA","eventClassifierCode":"EST","classifierDateTime":"2023-03-22T11:30:00"}],"facility":{"locationType":"TERMINAL","locationName":"Salalah Terminal","carrierTerminalCode":"OMSLVTM","carrierTerminalGeoID":"2LU3R3RRU5RVI","countryCode":"OM","countryName":"Oman","cityName":"Salalah","portName":"Salalah","carrierCityGeoID":"30ECXPXBQJMHO","UNLocationCode":"OMSLL"},"transport":{"inboundService":{"carrierVoyageNumber":"306E","carrierServiceCode":"600","carrierServiceName":"MECL"},"outboundService":{"carrierVoyageNumber":"306E","carrierServiceCode":"600","carrierServiceName":"MECL"}}},{"callSchedules":[{"transportEventTypeCode":"ARRI","eventClassifierCode":"EST","classifierDateTime":"2023-03-25T06:00:00"},{"transportEventTypeCode":"DEPA","eventClassifierCode":"EST","classifierDateTime":"2023-03-26T02:00:00"}],"facility":{"locationType":"TERMINAL","locationName":"Jebel Ali Terminal 2","carrierTerminalCode":"AEJALT2","carrierTerminalGeoID":"035ZCENG0J317","countryCode":"AE","countryName":"United Arab Emirates","cityName":"Jebel Ali","portName":"Jebel Ali","carrierCityGeoID":"31RTK5H2BLBS3","UNLocationCode":"AEJEA"},"transport":{"inboundService":{"carrierVoyageNumber":"306E","carrierServiceCode":"600","carrierServiceName":"MECL"},"outboundService":{"carrierVoyageNumber":"312W","carrierServiceCode":"600","carrierServiceName":"MECL"}}},{"callSchedules":[{"transportEventTypeCode":"ARRI","eventClassifierCode":"EST","classifierDateTime":"2023-03-28T09:00:00"},{"transportEventTypeCode":"DEPA","eventClassifierCode":"EST","classifierDateTime":"2023-03-29T11:00:00"}],"facility":{"locationType":"TERMINAL","locationName":"Port Qasim Terminal","carrierTerminalCode":"PKPQ1TM","carrierTerminalGeoID":"2P6HZUCGKJ42M","countryCode":"PK","countryName":"Pakistan","cityName":"Port Qasim","portName":"Port Qasim","carrierCityGeoID":"3FQ5D7WV73R3S","UNLocationCode":"PKQCT"},"transport":{"inboundService":{"carrierVoyageNumber":"306E","carrierServiceCode":"600","carrierServiceName":"MECL"},"outboundService":{"carrierVoyageNumber":"312W","carrierServiceCode":"600","carrierServiceName":"MECL"}}},{"callSchedules":[{"transportEventTypeCode":"ARRI","eventClassifierCode":"EST","classifierDateTime":"2023-03-31T04:00:00"},{"transportEventTypeCode":"DEPA","eventClassifierCode":"EST","classifierDateTime":"2023-03-31T22:00:00"}],"facility":{"locationType":"TERMINAL","locationName":"Pipavav Terminal","carrierTerminalCode":"INPPVTM","carrierTerminalGeoID":"1CGC6GKQ02IGW","countryCode":"IN","countryName":"India","cityName":"Pipavav","portName":"Pipavav","carrierCityGeoID":"1QF1SC3MCQHUZ","UNLocationCode":"INPPV","UNRegionCode":"GJ"},"transport":{"inboundService":{"carrierVoyageNumber":"306E","carrierServiceCode":"600","carrierServiceName":"MECL"},"outboundService":{"carrierVoyageNumber":"312W","carrierServiceCode":"600","carrierServiceName":"MECL"}}},{"callSchedules":[{"transportEventTypeCode":"ARRI","eventClassifierCode":"EST","classifierDateTime":"2023-04-02T04:00:00"},{"transportEventTypeCode":"DEPA","eventClassifierCode":"EST","classifierDateTime":"2023-04-03T07:00:00"}],"facility":{"locationType":"TERMINAL","locationName":"Jawaharlal Nehru NSICT DPW","carrierTerminalCode":"INJHTTM","carrierTerminalGeoID":"20JWFD10UBY3H","countryCode":"IN","countryName":"India","cityName":"Jawaharlal Nehru","portName":"Jawaharlal Nehru","carrierCityGeoID":"20JS07ETK8AE1","UNLocationCode":"INNSA","UNRegionCode":"MH"},"transport":{"inboundService":{"carrierVoyageNumber":"306E","carrierServiceCode":"600","carrierServiceName":"MECL"},"outboundService":{"carrierVoyageNumber":"312W","carrierServiceCode":"600","carrierServiceName":"MECL"}}},{"callSchedules":[{"transportEventTypeCode":"ARRI","eventClassifierCode":"EST","classifierDateTime":"2023-04-05T23:00:00"},{"transportEventTypeCode":"DEPA","eventClassifierCode":"EST","classifierDateTime":"2023-04-06T15:00:00"}],"facility":{"locationType":"TERMINAL","locationName":"Salalah Terminal","carrierTerminalCode":"OMSLVTM","carrierTerminalGeoID":"2LU3R3RRU5RVI","countryCode":"OM","countryName":"Oman","cityName":"Salalah","portName":"Salalah","carrierCityGeoID":"30ECXPXBQJMHO","UNLocationCode":"OMSLL"},"transport":{"inboundService":{"carrierVoyageNumber":"312W","carrierServiceCode":"600","carrierServiceName":"MECL"},"outboundService":{"carrierVoyageNumber":"312W","carrierServiceCode":"600","carrierServiceName":"MECL"}}},{"callSchedules":[{"transportEventTypeCode":"ARRI","eventClassifierCode":"EST","classifierDateTime":"2023-04-10T23:00:00"},{"transportEventTypeCode":"DEPA","eventClassifierCode":"EST","classifierDateTime":"2023-04-11T15:00:00"}],"facility":{"locationType":"TERMINAL","locationName":"Canal Zone Terminal","carrierTerminalCode":"EGSUCCN","carrierTerminalGeoID":"3792U3SWTPXA8","countryCode":"EG","countryName":"Egypt","cityName":"Suez Canal","portName":"Suez Canal","carrierCityGeoID":"0DOPTVWPU73B2"},"transport":{"inboundService":{"carrierVoyageNumber":"312W","carrierServiceCode":"600","carrierServiceName":"MECL"},"outboundService":{"carrierVoyageNumber":"312W","carrierServiceCode":"600","carrierServiceName":"MECL"}}},{"callSchedules":[{"transportEventTypeCode":"ARRI","eventClassifierCode":"EST","classifierDateTime":"2023-04-15T20:00:00"},{"transportEventTypeCode":"DEPA","eventClassifierCode":"EST","classifierDateTime":"2023-04-16T14:00:00"}],"facility":{"locationType":"TERMINAL","locationName":"Algeciras - ML Terminal","carrierTerminalCode":"ESALRTM","carrierTerminalGeoID":"0NTE1JGVL9NBT","countryCode":"ES","countryName":"Spain","cityName":"Algeciras","portName":"Algeciras","carrierCityGeoID":"05R47F3DBN69Q","UNLocationCode":"ESALG"},"transport":{"inboundService":{"carrierVoyageNumber":"312W","carrierServiceCode":"600","carrierServiceName":"MECL"},"outboundService":{"carrierVoyageNumber":"312W","carrierServiceCode":"600","carrierServiceName":"MECL"}}}]}

*~*~*~*~*~*~*~*~*~*
Darrell Ortiz
CDM Software Solutions, Inc.
https://www.cdmsoft.com
Posts: 1816
Joined: Wed Oct 26, 2005 02:49 PM
Re: Help with complex JSON
Posted: Tue Mar 21, 2023 02:20 PM
an idea
Code (fw): Select all Collapse
#include "fivewin.ch"

STATIC oWnd, oBmp, oSay, oBrush

FUNCTION Main()

Local aRsp := aReadjson()

xbrowse(aRsp)

RETURN NIL

Function aReadjson()
Local aRsp := {}
Local cPtJson := memoread("ayuda_foro.json")
Local hDtJson := {=>}
Local aFacility := {}
Local aTransport := {}
Local aCalls := {}
Local hChange:= {=>}
Local r := 0

hb_jsondecode(cPtJson ,@hDtJson ) 

aCalls := hDtJson["vesselCalls"]
for r:=1 to len(aCalls)
    
    aFacility := aCalls[r]["facility"]
    aTransport := aCalls[r]["transport"]

    if HHasKey( aFacility, "UNLocationCode" )
        hChange[ "FLD_POUL" ] := aFacility[ "UNLocationCode" ]
    else
        hChange[ "FLD_POUL" ] := "Undefined" //does not contain element
    endif
    if HHasKey( aFacility, "portName" )
        hChange[ "FLD_POULNAME" ] := aFacility[ "portName" ]
    else
        hChange[ "FLD_POULNAME" ] := "Undefined"
    endif

    hChange[ "FLD_VOYAGE" ] := aTransport[ "outboundService" ][ "carrierVoyageNumber"]
    hChange[ "FLD_SERVICE" ] := aTransport[ "outboundService" ][ "carrierServiceCode"]

    AAdd( aRsp, hChange )
    hChange := {=>}

next

Return aRsp
Saludos
LEANDRO AREVALO
Bogotá (Colombia)
https://hymlyma.com
https://hymplus.com/
leandroalfonso111@gmail.com
leandroalfonso111@hotmail.com

[ Turbo Incremental Link64 6.98 Embarcadero 7.70 ] [ FiveWin 25.01 ] [ xHarbour 64 bits) ]
Posts: 708
Joined: Fri Oct 28, 2005 09:53 AM
Re: Help with complex JSON
Posted: Tue Mar 21, 2023 02:42 PM

Thank you Leandro!

*~*~*~*~*~*~*~*~*~*
Darrell Ortiz
CDM Software Solutions, Inc.
https://www.cdmsoft.com
Posts: 990
Joined: Thu Nov 17, 2005 05:49 PM
Re: Help with complex JSON
Posted: Tue Mar 21, 2023 08:58 PM
In case it helps...
Anytime I want to debug Json data, I first open the string using notepad++ and under plugins, I use Json formatter. You can do the same with VsCode editor. Doing this with your sample string yields this:
Code (fw): Select all Collapse
{
    "vessel": {
        "vesselIMONumber": "9332999",
        "carrierVesselCode": "Q4F",
        "vesselName": "MAERSK DENVER",
        "vesselFlagCode": "US",
        "vesselCallSign": "WMDQ"
    },
    "vesselCalls": [
        {
            "callSchedules": [
                {
                    "transportEventTypeCode": "ARRI",
                    "eventClassifierCode": "EST",
                    "classifierDateTime": "2023-03-21T20:30:00"
                },
                {
                    "transportEventTypeCode": "DEPA",
                    "eventClassifierCode": "EST",
                    "classifierDateTime": "2023-03-22T11:30:00"
                }
            ],
            "facility": {
                "locationType": "TERMINAL",
                "locationName": "Salalah Terminal",
                "carrierTerminalCode": "OMSLVTM",
                "carrierTerminalGeoID": "2LU3R3RRU5RVI",
                "countryCode": "OM",
                "countryName": "Oman",
                "cityName": "Salalah",
                "portName": "Salalah",
                "carrierCityGeoID": "30ECXPXBQJMHO",
                "UNLocationCode": "OMSLL"
            },
            "transport": {
                "inboundService": {
                    "carrierVoyageNumber": "306E",
                    "carrierServiceCode": "600",
                    "carrierServiceName": "MECL"
                },
                "outboundService": {
                    "carrierVoyageNumber": "306E",
                    "carrierServiceCode": "600",
                    "carrierServiceName": "MECL"
                }
            }
        },
        {
            "callSchedules": [
                {
                    "transportEventTypeCode": "ARRI",
                    "eventClassifierCode": "EST",
                    "classifierDateTime": "2023-03-25T06:00:00"
                },
                {
                    "transportEventTypeCode": "DEPA",
                    "eventClassifierCode": "EST",
                    "classifierDateTime": "2023-03-26T02:00:00"
                }
            ],
            "facility": {
                "locationType": "TERMINAL",
                "locationName": "Jebel Ali Terminal 2",
                "carrierTerminalCode": "AEJALT2",
                "carrierTerminalGeoID": "035ZCENG0J317",
                "countryCode": "AE",
                "countryName": "United Arab Emirates",
                "cityName": "Jebel Ali",
                "portName": "Jebel Ali",
                "carrierCityGeoID": "31RTK5H2BLBS3",
                "UNLocationCode": "AEJEA"
            },
            "transport": {
                "inboundService": {
                    "carrierVoyageNumber": "306E",
                    "carrierServiceCode": "600",
                    "carrierServiceName": "MECL"
                },
                "outboundService": {
                    "carrierVoyageNumber": "312W",
                    "carrierServiceCode": "600",
                    "carrierServiceName": "MECL"
                }
            }
        },
        {
            "callSchedules": [
                {
                    "transportEventTypeCode": "ARRI",
                    "eventClassifierCode": "EST",
                    "classifierDateTime": "2023-03-28T09:00:00"
                },
                {
                    "transportEventTypeCode": "DEPA",
                    "eventClassifierCode": "EST",
                    "classifierDateTime": "2023-03-29T11:00:00"
                }
            ],
            "facility": {
                "locationType": "TERMINAL",
                "locationName": "Port Qasim Terminal",
                "carrierTerminalCode": "PKPQ1TM",
                "carrierTerminalGeoID": "2P6HZUCGKJ42M",
                "countryCode": "PK",
                "countryName": "Pakistan",
                "cityName": "Port Qasim",
                "portName": "Port Qasim",
                "carrierCityGeoID": "3FQ5D7WV73R3S",
                "UNLocationCode": "PKQCT"
            },
            "transport": {
                "inboundService": {
                    "carrierVoyageNumber": "306E",
                    "carrierServiceCode": "600",
                    "carrierServiceName": "MECL"
                },
                "outboundService": {
                    "carrierVoyageNumber": "312W",
                    "carrierServiceCode": "600",
                    "carrierServiceName": "MECL"
                }
            }
        },
        {
            "callSchedules": [
                {
                    "transportEventTypeCode": "ARRI",
                    "eventClassifierCode": "EST",
                    "classifierDateTime": "2023-03-31T04:00:00"
                },
                {
                    "transportEventTypeCode": "DEPA",
                    "eventClassifierCode": "EST",
                    "classifierDateTime": "2023-03-31T22:00:00"
                }
            ],
            "facility": {
                "locationType": "TERMINAL",
                "locationName": "Pipavav Terminal",
                "carrierTerminalCode": "INPPVTM",
                "carrierTerminalGeoID": "1CGC6GKQ02IGW",
                "countryCode": "IN",
                "countryName": "India",
                "cityName": "Pipavav",
                "portName": "Pipavav",
                "carrierCityGeoID": "1QF1SC3MCQHUZ",
                "UNLocationCode": "INPPV",
                "UNRegionCode": "GJ"
            },
            "transport": {
                "inboundService": {
                    "carrierVoyageNumber": "306E",
                    "carrierServiceCode": "600",
                    "carrierServiceName": "MECL"
                },
                "outboundService": {
                    "carrierVoyageNumber": "312W",
                    "carrierServiceCode": "600",
                    "carrierServiceName": "MECL"
                }
            }
        },
        {
            "callSchedules": [
                {
                    "transportEventTypeCode": "ARRI",
                    "eventClassifierCode": "EST",
                    "classifierDateTime": "2023-04-02T04:00:00"
                },
                {
                    "transportEventTypeCode": "DEPA",
                    "eventClassifierCode": "EST",
                    "classifierDateTime": "2023-04-03T07:00:00"
                }
            ],
            "facility": {
                "locationType": "TERMINAL",
                "locationName": "Jawaharlal Nehru NSICT DPW",
                "carrierTerminalCode": "INJHTTM",
                "carrierTerminalGeoID": "20JWFD10UBY3H",
                "countryCode": "IN",
                "countryName": "India",
                "cityName": "Jawaharlal Nehru",
                "portName": "Jawaharlal Nehru",
                "carrierCityGeoID": "20JS07ETK8AE1",
                "UNLocationCode": "INNSA",
                "UNRegionCode": "MH"
            },
            "transport": {
                "inboundService": {
                    "carrierVoyageNumber": "306E",
                    "carrierServiceCode": "600",
                    "carrierServiceName": "MECL"
                },
                "outboundService": {
                    "carrierVoyageNumber": "312W",
                    "carrierServiceCode": "600",
                    "carrierServiceName": "MECL"
                }
            }
        },
        {
            "callSchedules": [
                {
                    "transportEventTypeCode": "ARRI",
                    "eventClassifierCode": "EST",
                    "classifierDateTime": "2023-04-05T23:00:00"
                },
                {
                    "transportEventTypeCode": "DEPA",
                    "eventClassifierCode": "EST",
                    "classifierDateTime": "2023-04-06T15:00:00"
                }
            ],
            "facility": {
                "locationType": "TERMINAL",
                "locationName": "Salalah Terminal",
                "carrierTerminalCode": "OMSLVTM",
                "carrierTerminalGeoID": "2LU3R3RRU5RVI",
                "countryCode": "OM",
                "countryName": "Oman",
                "cityName": "Salalah",
                "portName": "Salalah",
                "carrierCityGeoID": "30ECXPXBQJMHO",
                "UNLocationCode": "OMSLL"
            },
            "transport": {
                "inboundService": {
                    "carrierVoyageNumber": "312W",
                    "carrierServiceCode": "600",
                    "carrierServiceName": "MECL"
                },
                "outboundService": {
                    "carrierVoyageNumber": "312W",
                    "carrierServiceCode": "600",
                    "carrierServiceName": "MECL"
                }
            }
        },
        {
            "callSchedules": [
                {
                    "transportEventTypeCode": "ARRI",
                    "eventClassifierCode": "EST",
                    "classifierDateTime": "2023-04-10T23:00:00"
                },
                {
                    "transportEventTypeCode": "DEPA",
                    "eventClassifierCode": "EST",
                    "classifierDateTime": "2023-04-11T15:00:00"
                }
            ],
            "facility": {
                "locationType": "TERMINAL",
                "locationName": "Canal Zone Terminal",
                "carrierTerminalCode": "EGSUCCN",
                "carrierTerminalGeoID": "3792U3SWTPXA8",
                "countryCode": "EG",
                "countryName": "Egypt",
                "cityName": "Suez Canal",
                "portName": "Suez Canal",
                "carrierCityGeoID": "0DOPTVWPU73B2"
            },
            "transport": {
                "inboundService": {
                    "carrierVoyageNumber": "312W",
                    "carrierServiceCode": "600",
                    "carrierServiceName": "MECL"
                },
                "outboundService": {
                    "carrierVoyageNumber": "312W",
                    "carrierServiceCode": "600",
                    "carrierServiceName": "MECL"
                }
            }
        },
        {
            "callSchedules": [
                {
                    "transportEventTypeCode": "ARRI",
                    "eventClassifierCode": "EST",
                    "classifierDateTime": "2023-04-15T20:00:00"
                },
                {
                    "transportEventTypeCode": "DEPA",
                    "eventClassifierCode": "EST",
                    "classifierDateTime": "2023-04-16T14:00:00"
                }
            ],
            "facility": {
                "locationType": "TERMINAL",
                "locationName": "Algeciras - ML Terminal",
                "carrierTerminalCode": "ESALRTM",
                "carrierTerminalGeoID": "0NTE1JGVL9NBT",
                "countryCode": "ES",
                "countryName": "Spain",
                "cityName": "Algeciras",
                "portName": "Algeciras",
                "carrierCityGeoID": "05R47F3DBN69Q",
                "UNLocationCode": "ESALG"
            },
            "transport": {
                "inboundService": {
                    "carrierVoyageNumber": "312W",
                    "carrierServiceCode": "600",
                    "carrierServiceName": "MECL"
                },
                "outboundService": {
                    "carrierVoyageNumber": "312W",
                    "carrierServiceCode": "600",
                    "carrierServiceName": "MECL"
                }
            }
        }
    ]
}
Only that inside the editor it is also color coded and a lot easier to follow.

Reinaldo.
Posts: 708
Joined: Fri Oct 28, 2005 09:53 AM
Re: Help with complex JSON
Posted: Tue Mar 21, 2023 09:03 PM

Hey Reinaldo, nice to hear from you. Thanks for your help!

*~*~*~*~*~*~*~*~*~*
Darrell Ortiz
CDM Software Solutions, Inc.
https://www.cdmsoft.com
Posts: 708
Joined: Fri Oct 28, 2005 09:53 AM
Re: Help with complex JSON
Posted: Wed Mar 22, 2023 02:51 AM

Thank you so much for your help! I am now able to pull all the data and displays in xbrowse. Now for a dumb question, how do I extract values from aRsp using FOR...NEXT so I can save ["imo"],["Vessel"],["Flag"],["Callsign"],["Vcode"],["ETA"],etc. to a DBF? I am sure it is very simple, I am new to JSON decoding.

Thanks in advance for your help!

//-----------------------------------------------------------------------------

Function aReadjson( cJson )

Local aRsp := {}

Local cPtJson := memoread(cJson)

Local hDtJson := {=>}

Local aSchedule := {}

Local aFacility := {}

Local aTransport := {}

Local aCalls := {}

Local hChange:= {=>}

Local r := 0, s := 0

local aVessel

hb_jsondecode(cPtJson ,@hDtJson )

aVessel := hDtJson["vessel"]

aCalls := hDtJson["vesselCalls"]

for r:=1 to len(aCalls)

        hChange["IMO"]      := aVessel["vesselIMONumber"]

        hChange["Vessel"]   := aVessel["vesselName"]

        hChange["Flag"]     := aVessel["vesselFlagCode"]

        hChange["Callsign"] := aVessel["vesselCallSign"]

        hChange["Vcode"]    := aVessel["carrierVesselCode"]



    aSchedule      := aCalls[r]["callSchedules"]

        FOR s:=1 TO LEN(aSchedule)

                IF (s=1)

                   hChange["ETA"]   := aSchedule[s]["classifierDateTime"]

                   hChange["ETA_TZ"] := aSchedule[s]["eventClassifierCode"]

                ENDIF

                IF (s=2)

                   hChange["ETD"]   := aSchedule[s]["classifierDateTime"]

                   hChange["ETD_TZ"] := aSchedule[s]["eventClassifierCode"]

                ENDIF

        NEXT s



  aFacility      := aCalls[r]["facility"]

  aTransport     := aCalls[r]["transport"]



  if HHasKey( aFacility, "UNLocationCode" )

     hChange[ "PortCode" ] := aFacility[ "UNLocationCode" ]

   else

     hChange[ "PortCode" ] := "Undefined" //does not contain element

  endif

  if HHasKey( aFacility, "portName" )

     hChange[ "PortName" ] := aFacility[ "portName" ]

   else

     hChange[ "PortName" ] := "Undefined"

  endif



  hChange[ "Voyage" ] := aTransport[ "outboundService" ][ "carrierVoyageNumber"]

  hChange[ "Service" ] := aTransport[ "outboundService" ][ "carrierServiceCode"]



  AAdd( aRsp, hChange )

  hChange := {=>}

next

RETURN aRsp

*~*~*~*~*~*~*~*~*~*
Darrell Ortiz
CDM Software Solutions, Inc.
https://www.cdmsoft.com
Posts: 10733
Joined: Sun Nov 19, 2006 05:22 AM
Re: Help with complex JSON
Posted: Thu Mar 23, 2023 10:10 AM
Anytime I want to debug Json data, I first open the string using notepad++ and under plugins, I use Json formatter. You can do the same with VsCode editor. Doing this with your sample string yields this:
Thanks for the useful information.

It is also possible to get a similar view with FWH/Harbour using a very simple function:
Code (fw): Select all Collapse
function JsonView( cJson )

   local h

   if hb_jsonDecode( cJson, @h ) > 0
      cJson    := hb_jsonEncode( h, .t. )
      FW_MEMOEDIT( cJson, "JSON" )
   else
      ? "Not Json text"
   endif

return nil
Regards



G. N. Rao.

Hyderabad, India
Posts: 708
Joined: Fri Oct 28, 2005 09:53 AM
Re: Help with complex JSON
Posted: Thu Mar 23, 2023 12:00 PM

Hi Rao,

Thank you! I was able to figure that part out. My question is how do I determine the structure of aRsp in Function aReadjson( cJson ) so I can retrieve the information within aRsp and save to DBF?

I appreciate your assistance with this.

*~*~*~*~*~*~*~*~*~*
Darrell Ortiz
CDM Software Solutions, Inc.
https://www.cdmsoft.com
Posts: 10733
Joined: Sun Nov 19, 2006 05:22 AM
Re: Help with complex JSON
Posted: Mon Mar 27, 2023 08:24 AM
This is my reply to your first post.
Glad if you can try this revised function ReadDataNew() as below:
Code (fw): Select all Collapse
static function ReadDataNew( hJson )

   local aData    := {}
   local aRow, aCalls, hCall, hFacility
   local d, n, i, j, aDt
   local ARRI, DEPA
   local cPol, cPolName, cDateTim, dEtd, cEtdTime

   aCalls      := hJson[ "vesselCalls" ]
   aEval( aCalls, { |h| hb_HSetCaseMatch( h, .f. ) } )

   for n  := 1 to Len( aCalls )
      hCall := aCalls[ n ]
      hFacility   := hCall[ "facility" ]
      hb_HSetCaseMatch( hFacility, .f. )

      if hCall[ "callSchedules" ][ 1 ][ "transportEventTypeCode" ] == "DEPA"
         DEPA  := 1
         ARRI  := 2
      else
         ARRI  := 1
         DEPA  := 2
      endif

      if n == 1
         cPol     := UNLCode( hFacility ) //hCall[ "facility" ][ "UNLocationCode" ]
         cPolName := hFacility[ "portName" ]
         cDateTim := hCall[ "callSchedules" ][ DEPA ][ "classifierDateTime" ]
      else
         // if hCall[ "facility" ][ "UNLocationCode" ] == cPol
         if UNLCode( hFacility ) ==  cPol
            if ( d := hCall[ "callSchedules" ][ DEPA ][ "classifierDateTime" ] ) > cDateTim
               cDateTim := d
            endif
         else
            if dEtd == nil
               aDt      := ParseDateTime( cDateTim )
               dEtd     := aDt[ 1 ]
               cEtdTime := aDt[ 2 ]
            endif
            aRow  := Array( 12 )
            aRow[ FLD_VESSEL   ]  := hJson[ "vessel" ][ "vesselName" ]
            aRow[ FLD_VOYAGE   ]  := hCall[ "transport" ][ "outboundService" ][ "carrierVoyageNumber" ]
            aRow[ FLD_LLOYDS   ]  := hJson[ "vessel" ][ "vesselIMONumber" ]
            aRow[ FLD_POL      ]  := cPol
            aRow[ FLD_POLNAME  ]  := cPolName
            aRow[ FLD_ETD      ]  := dEtd
            aRow[ FLD_ETDTIME  ]  := cEtdTime
            aRow[ FLD_POUL     ]  := UNLCode( hFacility ) //hCall[ "facility" ][ "UNLocationCode" ]
            aRow[ FLD_POULNAME ]  := hFacility[ "portName" ]
            aDt   := ParseDateTime( hCall[ "callSchedules" ][ ARRI ][ "classifierDateTime" ] )
            aRow[ FLD_ETA      ]  := aDt[ 1 ]
            aRow[ FLD_ETATIME  ]  := aDt[ 2 ]
            aRow[ FLD_SERVICE ] := hCall[ "transport" ][ "outboundService" ][ "carrierServiceCode" ]
            AAdd( aData, aRow )
         endif
      endif
   next

return aData

//----------------------------------------------------------------------------//

static function UNLCode( hFacility )

   if HHasKey( hFacility, "UNLocationCode" )
      return hFacility[ "UNLocationCode" ]
   endif

return "NA"

//----------------------------------------------------------------------------//

static function ParseDateTime( cDateTime )

   local dDate, cTime

   cTime    := SubStr( cDateTime, 12, 8 )
   dDate    := STOD( StrTran( Left( cDateTime, 10 ), "-", "" ) )

return { dDate, cTime }

//----------------------------------------------------------------------------//
It is likely to answer your second post also automatically.
Regards



G. N. Rao.

Hyderabad, India
Posts: 230
Joined: Thu Sep 17, 2015 11:40 PM
Re: Help with complex JSON
Posted: Sat Sep 23, 2023 04:17 PM
nageswaragunupudi wrote:This is my reply to your first post.
Glad if you can try this revised function ReadDataNew() as below:
Code (fw): Select all Collapse
static function ReadDataNew( hJson )

   local aData    := {}
   local aRow, aCalls, hCall, hFacility
   local d, n, i, j, aDt
   local ARRI, DEPA
   local cPol, cPolName, cDateTim, dEtd, cEtdTime

   aCalls      := hJson[ "vesselCalls" ]
   aEval( aCalls, { |h| hb_HSetCaseMatch( h, .f. ) } )

   for n  := 1 to Len( aCalls )
      hCall := aCalls[ n ]
      hFacility   := hCall[ "facility" ]
      hb_HSetCaseMatch( hFacility, .f. )

      if hCall[ "callSchedules" ][ 1 ][ "transportEventTypeCode" ] == "DEPA"
         DEPA  := 1
         ARRI  := 2
      else
         ARRI  := 1
         DEPA  := 2
      endif

      if n == 1
         cPol     := UNLCode( hFacility ) //hCall[ "facility" ][ "UNLocationCode" ]
         cPolName := hFacility[ "portName" ]
         cDateTim := hCall[ "callSchedules" ][ DEPA ][ "classifierDateTime" ]
      else
         // if hCall[ "facility" ][ "UNLocationCode" ] == cPol
         if UNLCode( hFacility ) ==  cPol
            if ( d := hCall[ "callSchedules" ][ DEPA ][ "classifierDateTime" ] ) > cDateTim
               cDateTim := d
            endif
         else
            if dEtd == nil
               aDt      := ParseDateTime( cDateTim )
               dEtd     := aDt[ 1 ]
               cEtdTime := aDt[ 2 ]
            endif
            aRow  := Array( 12 )
            aRow[ FLD_VESSEL   ]  := hJson[ "vessel" ][ "vesselName" ]
            aRow[ FLD_VOYAGE   ]  := hCall[ "transport" ][ "outboundService" ][ "carrierVoyageNumber" ]
            aRow[ FLD_LLOYDS   ]  := hJson[ "vessel" ][ "vesselIMONumber" ]
            aRow[ FLD_POL      ]  := cPol
            aRow[ FLD_POLNAME  ]  := cPolName
            aRow[ FLD_ETD      ]  := dEtd
            aRow[ FLD_ETDTIME  ]  := cEtdTime
            aRow[ FLD_POUL     ]  := UNLCode( hFacility ) //hCall[ "facility" ][ "UNLocationCode" ]
            aRow[ FLD_POULNAME ]  := hFacility[ "portName" ]
            aDt   := ParseDateTime( hCall[ "callSchedules" ][ ARRI ][ "classifierDateTime" ] )
            aRow[ FLD_ETA      ]  := aDt[ 1 ]
            aRow[ FLD_ETATIME  ]  := aDt[ 2 ]
            aRow[ FLD_SERVICE ] := hCall[ "transport" ][ "outboundService" ][ "carrierServiceCode" ]
            AAdd( aData, aRow )
         endif
      endif
   next

return aData

//----------------------------------------------------------------------------//

static function UNLCode( hFacility )

   if HHasKey( hFacility, "UNLocationCode" )
      return hFacility[ "UNLocationCode" ]
   endif

return "NA"

//----------------------------------------------------------------------------//

static function ParseDateTime( cDateTime )

   local dDate, cTime

   cTime    := SubStr( cDateTime, 12, 8 )
   dDate    := STOD( StrTran( Left( cDateTime, 10 ), "-", "" ) )

return { dDate, cTime }

//----------------------------------------------------------------------------//
It is likely to answer your second post also automatically.
HI,
[{"numEjercicio":"2023",
"desEstado":"No Presentado",
"lisPeriodos":[{"perTributario":"202309","codEstado":"03","desEstado":"No Presentado"},
{"perTributario":"202308","codEstado":"03","desEstado":"No Presentado"},
{"perTributario":"202307","codEstado":"03","desEstado":"No Presentado"},
{"perTributario":"202306","codEstado":"03","desEstado":"No Presentado"},
{"perTributario":"202305","codEstado":"03","desEstado":"No Presentado"}]}]

nLen := hb_jsonDecode(cRpta,@hJson)

HB_MEMOWRIT(::cPathDescarga+"respuesta.txt",cRpta)
FW_MEMOEDIT( hJson, "JSON" )

Error:
Error description: Error BASE/1108 Error de argumento: AT
Args:
[ 1] = C
[ 2] = A {{ "desEstado" => "No Presentado", "lisPeriodos" => {{ "codEstado" => "03", "desEstado" => "No ... } length: 1
Carlos Atuncar - CaSoftSystem
Chincha - Perú
+51983478218
carlosalbatun@gmail.com
Posts: 230
Joined: Thu Sep 17, 2015 11:40 PM
Re: Help with complex JSON
Posted: Sat Sep 23, 2023 09:13 PM

Solucionado

nLen := Len( oSire:jsonPeriodo )

hJson:= oSire:jsonPeriodo

If !Empty( nLen )

FOR EACH o IN hJson

  eje->(DBAppend())

  eje->ejercicio := o["numEjercicio"]

  eje->desestado := o["desEstado"]

  FOR EACH e IN o["lisPeriodos"]

     per->(DbAppend())

     per->ejercicio  := o["numEjercicio"]

     per->periodo    := e["perTributario"]

     per->codestado  := e["codEstado"]

     per->desestado  := e["desEstado"]

  NEXT

NEXT

EndIf

Carlos Atuncar - CaSoftSystem
Chincha - Perú
+51983478218
carlosalbatun@gmail.com
Posts: 400
Joined: Fri May 11, 2007 08:20 PM
Re: Help with complex JSON
Posted: Sun Oct 22, 2023 01:39 AM
Guys:
Mediante fwh como puedo descargar el archivo devuelto por una peticion en json?
Para llegar a descargar el archivo hago estos pasos
1. Genero un token (peticion post)
2. Solicito propuesta (informacion a consultar) termina esta peticion con un numero de ticket
3. Solicito el estado de ticket con el no. de ticket generado en el paso 2, termina con la respuesta del estado del ticket y el nombre del archivo a descargar (archivo zip)
4. Solicito descargar el archivo zip, esto me imprime la pantalla


Hice la prueba en postman y sale esto


Como hago para descargar el archivo mediante fwh?

Pego mi cod. fuente, espero me ayuden, gracias
Code (fw): Select all Collapse
    cId:="4ff4a1cd-1f8f-4436-8fb6-93e9769f3610"
    cPw:="fhlQo4u6929i21dyKwJa2w=="
    w_client_id=cId
    w_client_secret=cPw
    cUrl:="https://api-seguridad.sunat.gob.pe/v1/clientessol/"
    cUrl+=w_client_id
    cUrl+="/oauth2/token/"
    oHttp:Open( "POST", cUrl, .F.)
    ohttp:SetRequestHeader("content-type" , "application/x-www-form-urlencoded" )
    
    w_send := "grant_type=password&scope=https://api-sire.sunat.gob.pe&client_id="+w_client_id+"&client_secret="+w_client_secret+"&username=20554139834KREARINM&password=12345678"
    TRY
        ohttp:Send(w_send)   // ohttp:Send(enviar)
        IF oHttp:Status == 200
            Sysrefresh()
            XRespuesta:=ohttp:responseText
        ENDIF
    CATCH oError
        MsgAlert( oError:Description, Ptitle )
        RETURN (.F.)
    END                  
    aHasRes := hash()
    hb_jsondecode(XRespuesta ,@aHasRes) //Parse JSON to hash
    
    W_Token     := aHasRes["access_token"]

    ?"descargar propuesta"
    
    curl:="https://api-sire.sunat.gob.pe/v1/contribuyente/migeigv/libros/rce/propuesta/web/propuesta/202305/exportacioncomprobantepropuesta?codTipoArchivo=0&codOrigenEnvio=1&fecEmisionIni=2023-05-01&fecEmisionFin=2023-05-31&codTipo CDP=01"
    oHttp:Open( "GET", cUrl, .F.)
    ohttp:SetRequestHeader("Authorization" , "Bearer "+W_Token )
    ohttp:SetRequestHeader("Accept" , "application/json" )
    ohttp:SetRequestHeader("Content-Type" , "application/json" )
    TRY
        ohttp:Send()   // ohttp:Send(enviar)
        IF oHttp:Status == 200
            Sysrefresh()
            XRespuesta:=ohttp:responseText
            MsgAlert( XRespuesta, Ptitle )
        ENDIF
    CATCH oError
        MsgAlert( oError:Description, Ptitle )
        RETURN (.F.)
    END
    aHasRes := hash()
    hb_jsondecode(XRespuesta ,@aHasRes) //Parse JSON to hash
    
    W_NoTicket     := aHasRes["numTicket"]                  
    ?"consultar estado de ticket"
    cUrl:="https://api-sire.sunat.gob.pe/v1/contribuyente/migeigv/libros/rvierce/gestionprocesosmasivos/web/masivo/consultaestadotickets?perIni=202305&perFin=202305&page=1&perPage=20&numTicket="+W_NoTicket

    oHttp:Open( "GET", cUrl, .F.)
    ohttp:SetRequestHeader("Authorization" , "Bearer "+W_Token )
    ohttp:SetRequestHeader("Accept" , "application/json" )
    ohttp:SetRequestHeader("Content-Type" , "application/json" )
    TRY
        ohttp:Send()   // ohttp:Send(enviar)
        IF oHttp:Status == 200
            Sysrefresh()
            XRespuesta:=ohttp:responseText
            MsgAlert( XRespuesta, Ptitle )
        ENDIF
    CATCH oError
        MsgAlert( oError:Description, Ptitle )
        RETURN (.F.)
    END
    aHasRes := hash()
    hb_jsondecode(XRespuesta ,@aHasRes) //Parse JSON to hash
    aRegistros:=aHasRes["registros"]
    cEstado:=aRegistros[1]["desEstadoProceso"]
    cFile :=aRegistros[1]["archivoReporte"][1]["nomArchivoReporte"]

    ?"descargar archivo"

    cUrl:="https://api-sire.sunat.gob.pe/v1/contribuyente/migeigv/libros/rvierce/gestionprocesosmasivos/web/masivo/archivoreporte?nomArchivoReporte="
    cUrl+=cFile+"&codTipoArchivoReporte=null"

    oHttp:Open( "GET", cUrl, .F.)
    ohttp:SetRequestHeader("Authorization" , "Bearer "+W_Token )
    ohttp:SetRequestHeader("Accept" , "application/json" )
    ohttp:SetRequestHeader("Content-Type" , "application/json" )
    TRY
        ohttp:Send()   // ohttp:Send(enviar)
        IF oHttp:Status == 200
            Sysrefresh()
            XRespuesta:=ohttp:responseText
            MsgAlert( XRespuesta, Ptitle )
        ENDIF
    CATCH oError
        MsgAlert( oError:Description, Ptitle )
        RETURN (.F.)
    END
    aHasRes := hash()
    hb_jsondecode(XRespuesta ,@aHasRes) //Parse JSON to hash
    ?aHasRes
fwh 17.12, harbour 3.2.0, pelles C, bcc7, Ms-Sql
Posts: 400
Joined: Fri May 11, 2007 08:20 PM
Re: Help with complex JSON
Posted: Mon Oct 23, 2023 06:10 AM
fwh 17.12, harbour 3.2.0, pelles C, bcc7, Ms-Sql

Continue the discussion