LiquidCode Moderator Team
Joined: 05 Dec 2000 Posts: 1751 Location: Space and Time
|
Posted: Mon Apr 10, 2017 2:01 pm Post subject: JSON Parser |
|
|
This is a very simple JSON parser. I'm sure it could be a lot better but I just wanted something quick. It only works with 1 level. If anyone has a better solution please post. Sorry for lack of commenting.
{"firstName":"Chris","lastName":"Gingerich"}
Code: |
#define function,json
#define command,json
#%t = @json(create)
#json write,%t,name,VDSFreak
#json write,%t,email,"chris@insuresign.com"
#info @json(text,%t)
#info @json(read,%t,email)
#stop
:json
#very simple JSON parser
#%t = @json(create)
# Creates a JSON ID (a list)
#%t = @json(read,<JSON ID>,<name>,<default value>)
#%t = @json(text,<JSON ID>)
#json loadfile,<JSON ID>,<File name>
#json write,<JSON ID>,<name>,<value>
#json savefile,<JSON ID>,<file name>
if @not(%1)
error 2
end
if @equal(%1,read)
if @not(%2)
error 2
end
%%_json_text = @text(%2)
#first try with ,
%%exit = @strslice(%%_json_text,@chr(34)%3@chr(34):@chr(34),@chr(34)@chr(44))
if @not(%%exit)
#then with }
%%exit = @strslice(%%_json_text,@chr(34)%3@chr(34):@chr(34),@chr(34)"}")
end
if @not(%%exit)
if %4
%%exit = %4
end
end
#end
exit %%exit
elsif @equal(%1,write)
if @not(%2)
error 2
end
#get the text from the list
%%_json_text = @trim(@text(%2))
%p = @pos(@chr(34)%3@chr(34):@chr(34),%%_json_text)
if @not(@greater(%p,0))
%c = @pos("}",%%_json_text)
if @equal(%%_json_text,"{}")
#if a new JSON string don't add the ,
%%exit = @strins(%%_json_text,%c,@chr(34)%3@chr(34):@chr(34)%4@chr(34))
else
%%exit = @strins(%%_json_text,%c,@chr(44)@chr(34)%3@chr(34):@chr(34)%4@chr(34))
end
list clear,%2
list add,%2,%%exit
exit
else
%l = @len(@chr(34)%3@chr(34):@chr(34)@chr(44))
%s = @sum(%l,@pred(%p))
%%p2 = @pred(@pos(@chr(34),%%_json_text,%s))
%e = @strdel(%%_json_text,%s,%%p2)
%%exit = @strins(%e,%s,%4)
list clear,%2
list add,%2,%%exit
exit
end
elsif @equal(%1,create)
%l = @new(list)
list add,%l,"{}"
exit %l
elsif @equal(%1,text)
if @not(%2)
error 2
end
exit @text(%2)
elsif @equal(%1,savefile)
if @not(@both(%2,%3))
error 2
end
list savefile,%2,%3
elsif @equal(%1,loadfile)
if @not(%2)
error 2
end
list loadfile,%2,%3
exit
end
exit
|
EDIT: Updated to use a list _________________ Chris
Http://theblindhouse.com |
|