ParseJSON error

I get an error when loading the following valid JSON string:

The string var JSONString contains the following text:

{
    "Lines": [
        {
            "index": 0,
            "nb": "9822",
            "size": 2,
            "position": {
                "default": 1,
                "layer": 0
            },
            "tags": {
                "time": "2010-07-13T15:38:07.000000Z",
               
                "id": "0"
            }
        },
        {
            "index": 1,
            "name": "Apple",
            "size": 39,
            "position": {
                "default": 1,
                "layer": 0
            },
            "tags": {
                "time": "2010-07-13T15:38:07.000000Z",
                "id": "0"
            }
        }
    ]
}

Var Lines() As Variant = ParseJSON(jsonString)

This gives an error:
An exception of class TypeMismatchException was not handled. The application must shut down.

Any ideas why? The JSON string is a valid one.

This doesn’t throw a TypeMismatch:

Var Lines As Dictionary = ParseJSON(jsonString)

Though honestly have no clue as a beginner how to proceed then (o;

When you remove the Lines: in your JSON then your Code works with:

[
    {
        "index": 0,
        "nb": "9822",
        "size": 2,
Var Lines() As Variant = ParseJSON(TextArea1.Text)

For Each Line as Dictionary in Lines
  If Line.HasKey("index") Then
    TextArea1.AddText(EndOfLine + "index: " + Str(Line.Value("index")))
  End If
Next

But I’m pretty sure most people here know better :wink:

This seems to do it somehow (o;

Var JSON As Dictionary = ParseJSON(TextArea1.Text)

Var Lines() As Variant = JSON.Value("Lines")

For Each Line As Dictionary in Lines
  TextArea1.AddText(EndOfLine + "index: " + Str(Line.Value("index")))
  TextArea1.AddText(EndOfLine + "size: " + Str(Line.Value("size")))
Next

But I’m no expert (o;

ParseJSON() returns a Variant, not a Variant()

That’s your problem.

It would be easier handled as

Var json As New JSONItem(jsonString)
2 Likes

I have no problem with this text

Var tx As String
tx = “your JSON”

Var d As New Dictionary
d = ParseJSON ( tx )

Is there a reason you’re not using the JSONItem class? It’s the same engine under the hood and handles these idiosyncrasies for you.

Var js as new JSONItem(jsonString)

If not js.IsArray then
    // bad format
    Return
End if

Var c as integer = js.count
For i as integer = 0 to c-1
    Var item as JSONItem = js.itemAt(i)
    
    Var name = item.Value("name")
Next i 
1 Like

Yep, it seems JSONItem is working fine.

Thank you all for the feedback!

2 Likes