Help with JSON items, my code works but looking for more expert opinions

Hello everyone,

I’ve searched in the forum and read the documentation but I’m still not sure about my code (that works), here is what I’m doing:

The JSON structure is

[{"name":"Product Name 1", "price":5.0, "operator":"Jack", "paid":1, "id":"1"},
{"nome":"Product Name 2, "price":8.0, "operator":"John", "paid":0, "id":"3"}]

From the local database, I extract some data recursively and put the result into a JSONItem with this code in the method db_get_table_content

Var tableContent As New JSONItem

...database query...

For Each row As DatabaseRow In result
   Var tableRow As New JSONItem
   tableRow.Value("name") = result.Column("name").StringValue
   tableRow.Value("price") = result.Column("price").DoubleValue
   tableRow.Value("operator") = result.Column("operator").StringValue
   tableRow.Value("paid") = result.Column("paid").StringValue
   tableRow.Value("id") =  result.Column("id").StringValue
   tableContent.Add(tableRow)
Next

After that, I check the number of items in the tableContent to return it’s value as a string

if tableContent.count > 0 Then
  return tableContent.ToString
Else
  return ""
End if

This string is received by another method that iterates the JSON to do some operations

Var tableContentJSON As String = db_get_table_content 

If tableContentJSON.IsEmpty = false Then
  Var content() As Variant 
  content = ParseJSON(tableContentJSON)
  
  For Each d As Dictionary In content
    
    Var name As String = d.Value("nome")
    .....

  Next
End If

I had to convert the JSONItem into a String and then parse it into a Variant array to be able to iterate and access its content with d.Value(key).

Again, this is working but anyone has a better method to iterate the JSON instead of the need to convert it into a string and pass into a Variant?

Thanks!

Ciao Stefano,
db_get_table_content can return a JSONItem

if tableContent.count > 0 Then
  return tableContent
Else
  return Nil
End if

So you can write:

Var tableContentJSON As JSONItem = db_get_table_content 

If tableContentJSON<>Nil Then
   
  For Each d As Dictionary In tableContentJSON
    
    Var name As String = d.Value("nome")
    .....

  Next
End If

Hello Antonio,

I tried, but then I get the error:

This object does not implement the Iterable interface and cannot be used in a For Each loop
For Each d As Dictionary In contenutoTavoloJSON