Page 1 of 1

Parse JSON object with array HELP!

Posted: Thu Dec 15, 2022 11:36 pm
by ruslanx
Hi, need help !?

how I can parse in structure and load-save from-to file example "client,json"

Code: Select all

{
  "proxy": "",
  "priority": "Z",
  "books": [{
    "type": "text",
    "id": "text",
    "label": "text",
    "value": "text"
  }, {
    "type": "text",
    "id": "text",
    "label": "text",
    "value": "text"
  }, {
    "type": "text",
    "id": "text",
    "label": null,
    "value": true
  }],
  "lang": 1
}

Code: Select all

Global WorkPath$ = GetPathPart(ProgramFilename())
Global ClientsFile$ = WorkPath$ + "client.json"

Structure CLIENT
  proxy.s
  priority.s  
  Array books.s(200)
  lang.l  
EndStructure

Global CL.CLIENT

; Load
If LoadJSON(#JSON_Load, ClientsFile$)  
 ExtractJSONStructure(JSONValue(#JSON_Load), @CL, CLIENT)  
  Debug CL\priority
  Debug CL\books(1)   ; ????
  FreeJSON(#JSON_Load)
EndIf 

; Save
If CreateJSON(#JSON_Write) 
  InsertJSONStructure(JSONValue(#JSON_Write), @CL, CLIENT)     
  SaveJSON(#JSON_Write, ClientsFile$, #PB_JSON_PrettyPrint)
  FreeJSON(#JSON_Write)
EndIf  
I tried this code, but ... in javascript its easy .. here I dont know .. how to do this correctly .. please help

Re: Parse JSON object with array HELP!

Posted: Fri Dec 16, 2022 12:07 am
by Paul
You have no structure for your book data.
Personally I would put it in a list instead of array.

Code: Select all

Global WorkPath$ = GetPathPart(ProgramFilename())
Global ClientsFile$ = WorkPath$ + "client.json"

Structure booksdat
  type.s
  id.s
  label.s
  value.s
EndStructure

Structure CLIENT
  proxy.s
  priority.s  
  List books.booksdat()
  lang.l  
EndStructure

Global CL.CLIENT
#JSON_Load=1


; Load
If LoadJSON(#JSON_Load, ClientsFile$)  
 ExtractJSONStructure(JSONValue(#JSON_Load), @CL, CLIENT)  
  Debug CL\priority
  ForEach CL\books()
    Debug CL\books()\label
  Next
  FreeJSON(#JSON_Load)
EndIf