On Wednesday, March 25, 2015 at 1:03:53 PM UTC-4, Sid wrote:
> Does anybody have a MUMPS Routine that parses JSON strings into an array or global?
> Thanks
I know you asked about a Routine, but if you ever do need some in line code to handle it, I wrote something that can be pasted into the command line. I work with Epic and sometimes I don't have the ability to install a Routine. I use this code in a Print Group to call a Federal Poverty Index API and return some data, I also use it as a macro code to show the current temperature and conditions outside by calling the
wunderground.com API :)
Get the JSON:
s server="
fplapi.herokuapp.com",path="/api?size=3&income=1000&income_type=monthly",httprequest=##class(%Net.HttpRequest).%New(),httprequest.Server=server d httprequest.Get(path) s r=httprequest.HttpResponse.Data.Read()
Parse the JSON into a local variable called Rarray:
s st="f i=1:1:len s ch=$e(r,i) q:ch=""{""",ld="s level=level-1,j=i+1 f i=j:1:len s ch=$e(r,i) q:(ch=""}"")!(ch=""{"")!(ch="","")!(ch="""""""")!(ch="":"")",rs="s level=1,s=""""""""_$p($e(r,i,len),"""""""",2)_"""""""",j=i i 1 {f i=j:1:len s ch=$e(r,i) q:ch="":""} i 1 s ref=""Rarray(""_s_"")"",@ref=1",cc="s j=i+1,val="""" i 1 {f i=j:1:len s ch=$e(r,i) q:(ch=""}"")!(ch=""{"")!(ch="","")!(ch="""""""") s:(i=j)&(ch'="" "") val=val_ch s:(i>j) val=val_ch} i 1 s ref=""Rarray(""_s_"")"",@ref=$p(val,$c(10),1)",qc="s j=i+1,val="""",stop="""""""" i 1 {f i=j:1:len s ch=$e(r,i) s:ch="""""""" stop=1,ch=$e(r,i+1),i=i+1 q:stop=1 s val=val_ch} i 1 s ref=""Rarray(""_s_"")"",@ref=val i (ch'="","") s j=i f i=j:1:len s ch=$e(r,i) q:(ch="":"")!(ch="","")!(ch=""{"")!(ch=""}"")",lsq="s level=level+1,s=s_"",""""""_$p($e(r,i,len),"""""""",2)_"""""""",j=i i 1 {f i=j:1:len s ch=$e(r,i) q:ch="":""} i 1 s ref=""Rarray(""_s_"")"",@ref=1",cmc="s j=i+1,s=""""""""_$p($e(r,i,len),"""""""",2)_"""""""",ref=""Rarray(""_s_"")"",@ref=1,@ref=1 f i=j:1:len s ch=$e(r,i) q:ch="":""",lc="s j=i+1,s=s_"",""""""_$p($e(r,i,len),"""""""",2)_"""""""" f i=j:1:len s ch=$e(r,i) q:ch="":""",bs="f jj=1:1:level-1 s:jj=1 ns=ns_$p(s,"","",jj) s:jj>1 ns=ns_"",""_$p(s,"","",jj)",len=$L(r),level="",ch="",s="",ns="",val="" x st f q:i=len x:(ch="}") ld x:(ch="{")&(level="") rs x:(ch="{")&(level=1) lsq x:(ch="{")&(level>1) lsq x:ch=":" cc x:ch="""" qc s ns="" x:(ch=",")&(level>1) bs s:(ch=",")&(level>1) s=ns x:(ch=",")&(level>1) lc x:ch="," cmc
I have tested it on the weather API JSON response, which is a good amount of data, and it seems to get the structure perfectly. It should work correctly for any correctly formatted JSON.
I also just wanted to say I saw your stuff Rob Tweed after I wrote this and I might not have wasted so much time if I had saw your stuff first. I love that that you are a proponent for using Mumps (M) as a database. I think I am a fan of yours now.