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
203 stars 89 forks source link

Handling Arrays When Using Key Value Pairs #86

Closed DaveHopper closed 4 years ago

DaveHopper commented 5 years ago

Hi and thank you for an excellent library. I am trying to parse JSON responses from an api. Successful responses return an object which I can parse easily using json.pairs, however unsuccessful responses occasionally return an embedded array, which currently I am handling individually as per the below.

The name and quantity of embedded arrays sometimes changes which means that if my code encounters an array that I haven't handled it throws an error. I should state that I am simply writing the key/value pairs to a log file, so not knowing the exact structure ahead of time is only causing a problem when parsing the data, I am not doing any further processing of the data. I wondered if there was a way to iterate Objects and Arrays using a single method equivalent to json.pairs without having to set a variable for each array?

unsuccessful response; {""error"":""invalid_request"",""error_description"":""AADSTS900144: The request body must contain the following parameter: 'client_id'.\r\nTrace ID: 0f7d8231-1c9b-40c3-98e9-caa01a800d00\r\nCorrelation ID: 6a9defdc8-dshj082-40ef-8831-d1acbcfgaj394c0\r\nTimestamp: 2018-12-04 08:04:35Z"",""error_codes"":[900144],""timestamp"":""2018-12-04 08:04:35Z"",""trace_id"":""0f7d8231-1c9b-40c3-98e9-caa01a800d00"",""correlation_id"":""6a9stuc8-m082-40ek-8831-d1acbcdef394c0""}

` set json = new JSONobject json.parse(jsonString)

items = json.pairs

For each item in items

If item.name = "error_codes" Then

            Set arr = JSON("error_codes")

    For each item2 in arr.items
        json_msg = json_msg & item.name & " : " & item2 & "<br />"
        Next

                Else

json_msg = json_msg & item.name & " : " & item.value & "<br />"

End If

Next`

Many thanks and kind regards

rcdmk commented 5 years ago

Hi!

Unfortunately, VBS doesn't have a way to deal easily with objects and values the same way.

Maybe checking the property type before trying to access it would help.

DaveHopper commented 5 years ago

Hi, thank you for the quick response. With the JSON sample I've posted, checking using TypeName(item) returns JSONPair for all values, including the array, so that doesn't help me. I've also tried testing using IsObject with the same result.

Can you think of a reason why either method doesn't recognise the array? Do you have an alternative method I could try?

Thanks

rcdmk commented 5 years ago

Oh, I meant you could check the value property type in the jsonPair item. Sorry.