Page 1 of 1
How can I read JSON object containing keyed paired values ?
Posted: Sat Mar 15, 2025 3:30 am
by DEVP
The API returns a JSON object with product IDs as keys and their respective quantities as values? i.e keyed pair value.
i.e. { "product_id_1": "quantity_1", "product_id_2": "quantity_2", "product_id_3": "quantity_3"}
The following code only returns the quantity, and not the product IDs..
For Each(#Stock_levels) In(#Reader.ReadObjectWithPath( '/' ))
#QUANTITY := #Stock_levels.AsNumber
Endfor
From the example response ....
{
"109": "1.00000",
"110": "33.00000",
"114": "0.00000"
}
We are getting ...
#QUANTITY = 1.0
#QUANTITY = 33.0
#QUANTITY = 0.0
how do I also return the product IDs i.e "keys" i.e. 109, 110 and 114?
Thanks
Re: How can I read JSON object containing keyed paired values ?
Posted: Sat Mar 15, 2025 5:11 am
by cesarrafael
Hi DEVP,
Take a look at the "xDemoWebJsonViewer". Maybe it helps...
Re: How can I read JSON object containing keyed paired values ?
Posted: Mon Mar 17, 2025 1:33 pm
by Tim McEntee
Hi Devp
When you are extracting data from Name Value pairs usually you supply the Name and get the value. I'm not sure if you can run through the properties in an object using the X_PRIM Json tools. Someone might know how.
You could write code that reads the JSON string one char at a time. Trips would be "{" start object; "}" end object and end of quantity; ":" end of Product Id; "," end of quantity
Tim
Re: How can I read JSON object containing keyed paired values ?
Posted: Thu Mar 27, 2025 12:30 am
by DEVP
Thank you for the responses - I have resolved the issue by moving the response to NVARCHAR string field, then extracting the name and value pairs into an array thus :
Def_List Name(#List_Stock_Levels) Fields(#product_id #quantity) Counter(#LISTCOUNT) Type(*WORKING) Entrys(*MAX)
Define Field(#product_id) Reffld(#BSDPRID)
Define Field(#quantity) Reffld(#BSDQTY)
...
...
#jsonShipmentsObject <= #Reader.ReadObjectWithPath( '/' )
#ResultNVARCHAR := #jsonShipmentsObject.AsString
#STD_NUML #CPM_D1_0 := 1
Begin_Loop
#STD_NUML := #ResultNVARCHAR.PositionOf( '"', #STD_NUML )
Leave If(#STD_NUML = 0)
#STD_INT := #ResultNVARCHAR.PositionOf( '"', (#STD_NUML + 1) )
Leave If(#STD_INT = 0)
#STD_NVARC := #ResultNVARCHAR.Substring( (#STD_NUML + 1), (#STD_INT - (#STD_NUML + 1)) )
Case Of_Field(#CPM_D1_0)
When Value_Is(= 1)
#Product_Id := #STD_NVARC.AsNativeString
Otherwise
#quantity := #STD_NVARC.AsNumber
Add_Entry To_List(#List_Stock_Levels)
#CPM_D1_0 := 0
Endcase
#CPM_D1_0 += 1
#STD_NUML := #STD_INT + 1
End_Loop