Page 1 of 1
Crafting json http respinse
Posted: 11 Dec 2019 21:45
by jassing
This code fails, resulting in "{error}" being delivered as the response.
- Screenshot_20191211-001846.png (144.66 KiB) Viewed 9398 times
What is the preferred way to deliver the expected results?
Thanks.
Re: Crafting json http respinse
Posted: 12 Dec 2019 06:33
by Desmanto
Creating JSON directly from string is very challenging. You have to use single quote to quote the element, since double quote will try to parse the braces into variable. Many problems happen when you try to use inline expression. You also need several string concatenation and makes it difficult to read.
Although it is possible and maybe practical if the JSON is short; but just make it a good practice to create the object first in nested map/list. Later use toJSON() to convert it to JSON. It is clean, and you don't have to deal with the problem above.
I can't see your whole JSON there, so I will try to mimic the best. Put below into script before the response.
Code: Select all
obj = newMapFromValues(
"Date", dateymd,
"Times", newMapFromValues(
"AstronomicalDawn", "{Astronomical_Dawn,dateformat,HH:mm:ss}",
"NauticalDawn", "{Nautical_Dawn,dateformat,HH:mm:ss}",
"CivilDawn", "{Civil_dawn,dateformat,HH:mm:ss}",
"Sunrise", "{Sunrise,dateformat,HH:mm:ss}",
"Solarnoon", "{Solarnoon,dateformat,HH:mm:ss}",
"Sunset", "{Sunset,dateformat,HH:mm:ss}",
"CivilDusk", "{Civil_Dusk,dateformat,HH:mm:ss}",
"NauticalDusk", "{Nautical_Dusk,dateformat,HH:mm:ss}",
"AstronomicalDusk", "{Astronomical_Dusk,dateformat,HH:mm:ss}"
),
"LengthOfDay", "{getDurationString(Sunset - Sunrise)}"
);
json = toJSON(obj);
Use {json} in the write http response.
Re: Crafting json http respinse
Posted: 12 Dec 2019 07:51
by jassing
Thank you very much...
I was trying to return json-formatted text via write HTTP Response Text...
I really appreciate the example and explanation...
Re: Crafting json http respinse
Posted: 12 Dec 2019 19:24
by Micky Micky
I did this today and it took ages to figure that it was the [ ] brackets that were needed.
Might be of some help.
My cut and paste has made this look a bit odd. It's one long string without big spaces.
peopleList =
'{"people" :[{"name":"Micky","phone":"012345678","birthday":"0101"},{"name":"Mickey","phone":"12345678","birthday":"0202"},{"name":"Michael ","phone":"2345678","birthday":"0303"},{"name":"Micheal","phone":"345678","birthday":"0404"},{"name":"Mike","phone":"567890","birthday":"0505"}]}';
js = fromJSON (peopleList);
len = length (js["people"]);
name = js["people"][a]["name"];
phone = js["people"][a]["phone"];
birthday = js["people"][a]["birthday"];
a is the index
Re: Crafting json http respinse
Posted: 13 Dec 2019 00:08
by jassing
Wild... I don't think I would ever have guessed that... Good job. Thanks for sharing.