Question
· Sep 24, 2021

How to get Specific element from JSON file by Calling API from objectscript?

Hi

Following API:
http://api.aladhan.com/v1/gToH?date=24-09-2021
is returning following JSON response:
{"code":200,"status":"OK","data":{"hijri":{"date":"16-02-1443","format":"DD-MM-YYYY","day":"16","weekday":{"en":"Al Juma'a","ar":"\u0627\u0644\u062c\u0645\u0639\u0629"},"month":{"number":2,"en":"\u1e62afar","ar":"\u0635\u064e\u0641\u064e\u0631"},"year":"1443","designation":{"abbreviated":"AH","expanded":"Anno Hegirae"},"holidays":[]},"gregorian":{"date":"24-09-2021","format":"DD-MM-YYYY","day":"24","weekday":{"en":"Friday"},"month":{"number":9,"en":"September"},"year":"2021","designation":{"abbreviated":"AD","expanded":"Anno Domini"}}}}

How can I  get "hijri":{"date":"16-02-1443" portion from response JSON by calling above API by passing parameter date=24-09-2021 from objectscript?

Thanks
 

Product version: IRIS 2021.1
Discussion (8)1
Log in or sign up to continue

Hi Muhammad,

Create following class :

Class Test.Json
{

ClassMethod Get(date = "24-09-2021", debug = 0) As %String
{
  #Dim status as %Status
  #Dim response as %Stream
  #Dim jsonResponse as %DynamicObject Set objHttp = ##class(%Net.HttpRequest).%New()
  Set objHttp.Server="api.aladhan.com"
  Set objHttp.Https=0
  Do objHttp.SetParam("date",date)
  Set status = objHttp.Send("GET","v1/gToH")
  If status'=1 Do $SYSTEM.OBJ.DisplayError(status) Quit ""
  If objHttp.HttpResponse'="" Do
  Set response = objHttp.HttpResponse.Data
  Set jsonResponse = ..GetResponse(response)
  If debug Write jsonResponse.data.hijri.%ToJSON(),!
  Return jsonResponse.data.hijri.date
}

ClassMethod GetResponse(response As %Stream, del As %String = "") As %DynamicObject
{
  #Dim jsonStr as %String = ""
  If response'="" {
    Do response.Rewind()
    While 'response.AtEnd {
      Set jsonStr = jsonStr _ response.ReadLine() _ del
    }
  }
  Quit {}.%FromJSON(jsonStr)
}

}

and call it like :

USER>set hijri=##class(Test.Json).Get()
 
USER>write hijri
16-02-1443
USER>set hijri=##class(Test.Json).Get(,1)
{"date":"16-02-1443","format":"DD-MM-YYYY","day":"16","weekday":{"en":"Al Juma'a","ar":"الجمعة"},"month":{"number":2,"en":"Ṣafar","ar":"صَفَر"},"year":"1443","designation":{"abbreviated":"AH","expanded":"Anno Hegirae"},"holidays":[]}
 
USER>Write ##class(Test.Json).Get("01-08-2021")
22-12-1442
USER>