B4R Question rArduino_JSON, Get number of elements in array

Mostez

Well-Known Member
Licensed User
Longtime User
This question is about using rArduino_JSON library by @candide
If we have this Json string, how can we get the number of elements in array "dv"
JSON:
{"nam":"John Smith","id":"SDD01001","exp":"2512311400","ver":"1.40","dv":["ALX01001","ALX01002","ALX01003","ALX01004"]}

I tried this code but nDevs = -1

B4X:
    Dim nDevs As Int = Jparse.Length(Array(2,"dv"))
    Log("nDevices: ",nDevs)
    For m = 0 To nDevs -1
        Log("Device: ", Jparse.GetString(Array(2, "dv", m)))
    Next
 

emexes

Expert
Licensed User
Longtime User
If no luck doing it via the library, you could always do something like count the number of quotation marks between square brackets and divide by 2. 🫣
 
Last edited:
Upvote 0

emexes

Expert
Licensed User
Longtime User
eg like this Poor Man's JSON array size parser (done in B4J but with luck works in B4R too):
B4X:
Sub PoorMansJsonArraySize(Haystack As String, Needle As String ) As Int
    Dim ArrayStart As String = """" & Needle & """:["
    Dim ArrayEnd As String = "]"
   
    Dim P As Int = Haystack.IndexOf(ArrayStart)
    If P < 0 Then Return 0
   
    Dim Q As Int = Haystack.IndexOf2(ArrayEnd, P + ArrayStart.Length)
    If Q < 0 Then Return 0

    Dim NumQuotationMarks As Int = 0
    For I = P + ArrayStart.Length To Q - ArrayEnd.Length
        If Haystack.CharAt(I) = """" Then
            NumQuotationMarks = NumQuotationMarks + 1
        End If
    Next
   
    Return Bit.ShiftRight(NumQuotationMarks, 1)    'integer divide-by-2
End Sub
B4X:
Dim J As String = $"{"nam":"John Smith","id":"SDD01001","exp":"2512311400","ver":"1.40","dv":["ALX01001","ALX01002","ALX01003","ALX01004"]}"$
Log(PoorMansJsonArraySize(J, "dv"))
Log output:
Waiting for debugger to connect...
Program started.
4
 
Last edited:
Upvote 0

Mostez

Well-Known Member
Licensed User
Longtime User
I got it, I was trying to access dv with incorrect path. The dv array is at the root level. So array path should be Array(1, "dv")

B4X:
'Array(1, "dv") - To access the array itself (for getting its length)
'Array(2, "dv", m) - To access individual elements within the array

Dim nDevs As Int = Jparse.Length(Array(1,"dv")) ' Correct path is 1, not 2
    Log("nDevices: ",nDevs)
    For m = 0 To nDevs -1
        Log("Device: ", Jparse.GetString(Array(2, "dv", m))) 
    Next

Log output:
nDevices: 4
Device: ALX01001
Device: ALX01002
Device: ALX01003
Device: ALX01004
 
Upvote 0
Top