I have a hard time understanding the JSON library.
How can I fetch content : "\n\nThis is a test!" into a variable ?
It is always just one reply (variable) in the object.
In Python it would be content = json_data["choices"][0]["message"]["content"]
Thanks in advance
Spec: Linux Mint 20.3 Cinnamon, i7-3770K, 16GB RAM, RTX 2070 Super
Janni wrote:
How can I fetch content : "\n\nThis is a test!" into a variable ?
The easiest way probably is like so:
Save this module to a .pbi file, and include that file into your main code file, where you write the following code:
FILE$="json-file.json"
JSON = ReadFile(#PB_Any, FILE$)
If JSON
While Eof(JSON) = 0
JSON_STRING$ + ReadString(JSON)
Wend
CloseFile(JSON)
EndIf
;Debug JSON_STRING$
Structure usage ; Not used
prompt_tokens.s ; text or number
completion_tokens.s ; text or number
total_tokens.s ; text or number
EndStructure
NewMap usage()
Structure message
role.s
content.s
EndStructure
Structure choice
index.a
finish_reason.s
message.message
EndStructure
NewList choices.choice()
JSON = ParseJSON(#PB_Any, JSON_STRING$, #PB_JSON_NoCase)
If JSON
Debug "id : " +GetJSONString(GetJSONMember(JSONValue(JSON),"id"))
Debug "object : " +GetJSONString(GetJSONMember(JSONValue(JSON),"object"))
Debug "created : "+GetJSONString(GetJSONMember(JSONValue(JSON),"id"))
Debug "model : " +GetJSONString(GetJSONMember(JSONValue(JSON),"model"))
Debug ""
jsonObjectValue = GetJSONMember(JSONValue(JSON),"usage")
If jsonObjectValue
ExtractJSONMap(jsonObjectValue, usage())
Debug "prompt_tokens : " +usage("prompt_tokens")
Debug "completion_tokens : "+usage("completion_tokens")
Debug "total_tokens : " +usage("total_tokens")
Else
Debug "No 'usage' member !"
EndIf
Debug ""
;;;
jsonObjectValue = GetJSONMember(JSONValue(JSON),"choices")
If jsonObjectValue
ExtractJSONList(jsonObjectValue, choices())
With choices()
Debug "index : " +\index
Debug "finish reason : "+\finish_reason
Debug "role : " +\message\role
Debug "content : " +\message\content
EndWith
Else
Debug "No 'choices' member !"
EndIf
EndIf
Gérard
■ Win10 64-bit (Intel Celeron CPU N2920 @ 1.86GHz, 4,0GB RAM, Intel HD Graphics) & PB 6.00 LTS
■ Vivre et laisser vivre.
■ PureBasic pour le fun
■ cage sur le forum Français
■ Mes sites: http://pbcage.free.fr - http://yh.toolbox.free.fr