[done] Struggle parsing mixed type JSON array

Just starting out? Need help? Post your questions and find answers here.
User avatar
Kukulkan
Addict
Addict
Posts: 1396
Joined: Mon Jun 06, 2005 2:35 pm
Location: germany
Contact:

[done] Struggle parsing mixed type JSON array

Post 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!
Last edited by Kukulkan on Thu Aug 15, 2024 8:46 am, edited 1 time in total.
freak
PureBasic Team
PureBasic Team
Posts: 5940
Joined: Fri Apr 25, 2003 5:21 pm
Location: Germany

Re: Struggle parsing mixed type JSON array

Post 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
quidquid Latine dictum sit altum videtur
User avatar
Kukulkan
Addict
Addict
Posts: 1396
Joined: Mon Jun 06, 2005 2:35 pm
Location: germany
Contact:

Re: Struggle parsing mixed type JSON array

Post by Kukulkan »

It works, THANK YOU!!!
Post Reply