pbjson icon indicating copy to clipboard operation
pbjson copied to clipboard

how do I read json array which has no root entry

Open prashantnirgun opened this issue 3 years ago • 3 comments
trafficstars

my json array response is as follows [{"route":"Transaction","service_status":"Active","balance":82,"validity":"2022-08-11T18:30:00.000Z"},{"route":"Promotional","service_status":"Active","balance":100,"validity":"2022-12-30T18:30:00.000Z"}]

01 How do I access 2nd row and balance attribute 02 Is there is any way I can determine do I have how many rows I mean it might have one or more rows

I tried out this but didn't works ln_json.retrieve("/1/route", ref la_data)

prashantnirgun avatar Aug 19 '22 08:08 prashantnirgun

Hi, here is one way to do this :

ls_error = ln_json.parse('[{"route":"Transaction","service_status":"Active","balance":82,"validity":"2022-08-11T18:30:00.000Z"},{"route":"Promotional","service_status":"Active","balance":100,"validity":"2022-12-30T18:30:00.000Z"}]')
if ls_error = "" then
	if ln_json.isarray() then
		any la_array[]
		la_array[] = ln_json.getarray()
		messagebox("array length:", string( upperbound( la_array[] ) ) )
		ln_json.retrieve("1/route", ref la_data)
		string ls_route
		ls_route = la_data
		messagebox("1st route:", ls_route)
	end if
end if

xlat avatar Aug 21 '22 08:08 xlat

Thanks it works now had one more I if I had array as a element which hold array my code is as follows is there any better way to handle this?

int li_start, li_end
String ls_error, ls_response, ls_value
any la_data
any la_value
json ln_json

ln_json = create json
ls_response = '{"contents": [{"id" : "1", "name" : "one"},{ "id" : "2", "name" : "Two"}]}'
ls_error = ln_json.parse(ls_response)

if ls_error = "" then
	ln_json.retrieve("contents", ref la_data) 
	li_end = upperbound( la_data[])
	For li_start = 1 TO li_end
		ln_json.retrieve("contents/" + String(li_start) + "/name", ref la_value) 
		MessageBox("Info", "Name : " + String(la_value))
	NEXT
end if

destroy ln_json

prashantnirgun avatar Aug 22 '22 14:08 prashantnirgun

Hi, here is another way to do the same, using less retrieve() calls, so for huge array it should be faster:

int li_start, li_end
String ls_error, ls_response
any la_data, la_contents[]
json ln_json, ln_item

ln_json = create json
ls_response = '{"contents": [{"id" : "1", "name" : "one"},{ "id" : "2", "name" : "Two"}]}'
ls_error = ln_json.parse(ls_response)

if ls_error = "" then
	ln_json.retrieve("contents", ref la_data)
	la_contents[] = la_data
	li_end = upperbound( la_contents[] )
	For li_start = 1 TO li_end
		ln_item = la_contents[li_start]
		MessageBox("Info", "Name : " + string(ln_item.getattribute("name")))
	next
end if

destroy ln_json

xlat avatar Aug 23 '22 13:08 xlat