[Gambas-user] gb.web.JSONCollection parse problem
T Lee Davidson
t.lee.davidson at gmail.com
Thu Feb 21 22:44:20 CET 2019
On 2/21/19 2:54 PM, jeff zacher wrote:
> Two valid JSON files will not parse properly with a call to
>
> JSON.Decode(<json file contents>, True)
>
> Consider this is valid JSON:
> [
> {
> "name" : "Value",
> "another" : "Value"
> }
> ]
>
> The above will decode as a Variant[] and not a JSONCollection.
>
> Consider this other valid JSON:
>
> {
> "name" : "value",
> "another" : {
> "nestedname" : "value"
> }
> }
>
> These will return as JSONCollections.
>
> This is somewhat as expected, however there is no way to gracefully detect what type of object has been decoded. Using Try
> blocks to determine by trial and error which of the above forms of a JSON are present cannot be good programming form. The
> TypeOf(<json file contents>) function gives a gb.object type of object for both. This is very problematic when parsing large
> files. What is the proper work around or how is this been properly used in these cases (what am I missing about this?)
>
The first JSON content is actually not a Collection. It is an array (or list) of collections with only one element. So, it
decodes as a Variant.
You can test the type of the object using the "IS" operator which differentiates between both types, whereas TypeOf is lazy.
' Gambas module file
Public Sub Main()
Dim sJson1 As String = "[{\"name\": \"Value\", \"another\": \"Value\"}]"
Dim sJson2 As String = "{\"name\": \"value\", \"another\": {\"nestedname\": \"value\"}}"
Dim JsonResult As Variant
JsonResult = JSON.Decode(sJson1)
If JsonResult Is Collection Then
Print "Collection"
Else
Print "Array of Collections"
Endif
JsonResult = JSON.Decode(sJson2)
If JsonResult Is Collection Then
Print "Collection"
Else
Print "Array of Collections"
Endif
End
This code yields:
Array of Collections
Collection
___
Lee
More information about the User
mailing list