rcdmk / aspJSON

A fast classic ASP JSON parser and encoder for easy JSON manipulation to work with the new JavaScript MV* libraries and frameworks.
MIT License
204 stars 89 forks source link

JSON.Add in Loops #46

Closed alexvremja closed 7 years ago

alexvremja commented 7 years ago

Hi! I need to build such json payload: { "items": [ { "barcode": "AP108016035NL", "destination_country_code": "DE", "sender_reference": "hans001" }, { "barcode": "AP108016049NL", "destination_country_code": "FR", "sender_reference": "philippe002" }, { "barcode": "AP108016052NL", "destination_country_code": "ES", "sender_reference": "angel003" } ] }

surely there is a better solution but so far I built the following routine :

`barcodes=Array("AP108016035NL|DE|hans001","AP208016049NL|FR|philippe002","AP309145987NL|ES|angel003") Response.LCID = 1040 Set JSON= New JSONObject Set JSONB= New JSONObject Set JSONA= New JSONArray

for each barcode in barcodes bcA=split(barcode,"|") JSON.change "barcode",bcA(0) JSON.change "destination_country_code",bcA(1) JSON.change "sender_reference", bcA(2) 'JSON.write JSONA.push JSON 'response.write "
"&bca(0) next JSONB.add "items", JSONA JSONB.write`

the problem is that the result contains 3 times the latest data: {"items":[{"barcode":"AP309145987NL","destination_country_code":"ES","sender_reference":"angel003"},{"barcode":"AP309145987NL","destination_country_code":"ES","sender_reference":"angel003"},{"barcode":"AP309145987NL","destination_country_code":"ES","sender_reference":"angel003"}]}

I made many tests with JSONObject and JSONArray, but haven't find the solution. can pls suggest a solution? thanks

rcdmk commented 7 years ago

Hi. You almost got it. What you need to do is create a new instance of JSONObject for each loop iteration:

For Each barcode In barcodes
    bcA = Split(barcode, "|")
    JSON = New JSONObject
    JSON.Add "barcode", bcA(0)
    JSON.Add "destination_country_code", bcA(1)
    JSON.Add "sender_reference", bcA(2)
    JSONA.Push JSON
Next

JSONA.Write

Bests!

alexvremja commented 7 years ago

Works like a charm..

Thanks a lot!