Page 1 of 1

[done] Struggle parsing mixed type JSON array

Posted: Wed Aug 14, 2024 11:53 am
by Kukulkan
Hi. I get two types of JSON arrays as function parameter string:

Code: Select all

["val1", "val2"]
or

Code: Select all

["val3", 4]
I need to react on both types. But I struggle to even determine the type.

I tried several ways to parse, but with ExtractJSONArray, I get either the integer or the string value, but not both (depending on array type). If I use ExamineJSONMembers, I get an error because the strings are not an object.

How do I reliable parse such JSON strings? A short example would be great, thanks!

Re: Struggle parsing mixed type JSON array

Posted: Wed Aug 14, 2024 4:36 pm
by freak
ExamineJSONMembers() is the wrong function to use here because it is only for JSON Objects not for Arrays.

What you need is:
  • JSONArraySize() to find out the size of the array
  • GetJSONElement() to get the individual elements
  • JSONType() to find the type of the element
  • GetJSONInteger() or GetJSONString() to read the actual value depending on the type
This sounds more complex than it actually is. There is an example for reading a JSON Array with mixed types in the description of the JSONType() function. See here: https://www.purebasic.com/documentation ... ntype.html

Code: Select all

  ; A procedure that accepts any JSON value and returns a string
  ;
  Procedure.s GetAnyValue(Value)
    Select JSONType(Value)
      Case #PB_JSON_Null:    ProcedureReturn "null"
      Case #PB_JSON_String:  ProcedureReturn GetJSONString(Value)
      Case #PB_JSON_Number:  ProcedureReturn StrD(GetJSONDouble(Value))    
      Case #PB_JSON_Boolean: ProcedureReturn Str(GetJSONBoolean(Value))
      Case #PB_JSON_Array:   ProcedureReturn "array"
      Case #PB_JSON_Object:  ProcedureReturn "object"
    EndSelect
  EndProcedure
  
  ParseJSON(0, "[1, 2, true, null, " + Chr(34) + "hello" + Chr(34) + "]")
  For i = 0 To JSONArraySize(JSONValue(0)) - 1
    Debug GetAnyValue(GetJSONElement(JSONValue(0), i))
  Next i

Re: Struggle parsing mixed type JSON array

Posted: Wed Aug 14, 2024 6:46 pm
by Kukulkan
It works, THANK YOU!!!