Page 1 of 1

Fetching JSON value

Posted: Tue Aug 29, 2023 8:42 pm
by Janni

Code: Select all

{
    "id": "chatcmpl-abc123",
    "object": "chat.completion",
    "created": 1677858242,
    "model": "gpt-3.5-turbo-0613",
    "usage": {
        "prompt_tokens": 13,
        "completion_tokens": 7,
        "total_tokens": 20
    },
    "choices": [
        {
            "message": {
                "role": "assistant",
                "content": "\n\nThis is a test!"
            },
            "finish_reason": "stop",
            "index": 0
        }
    ]
}
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

Re: Fetching JSON value

Posted: Tue Aug 29, 2023 10:21 pm
by Little John
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:

Code: Select all

Define jn.i, s$
   
jn = LoadJSON(#PB_Any, "MyJSONdata.json")
If jn = 0
   Debug "Error: Can't load JSON file."
   End
EndIf   
   
s$ = JSON::Get(jn, "choices\[0]\message\content")
Debug s$

Re: Fetching JSON value

Posted: Wed Aug 30, 2023 1:03 am
by Gérard
I created a file from your data to analyze the data and extract each value.

Code: Select all

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

Re: Fetching JSON value

Posted: Wed Aug 30, 2023 6:06 am
by Paul
Assuming you saved your JSON data in a file called "dat.txt"

Code: Select all

Structure usagedata
  prompt_tokens.i
  completion_tokens.i
  total_tokens.i
EndStructure

Structure messagedata
  role.s
  content.s
EndStructure

Structure choicesdata
  message.messagedata
  finish_reason.s
  index.i
EndStructure

Structure jsondata
  id.s
  object.s
  created.i
  model.s
  usage.usagedata
  List choices.choicesdata()
EndStructure


hJSON= LoadJSON(#PB_Any, "dat.txt")
If hJSON
  ExtractJSONStructure(JSONValue(hJSON), @dat.jsondata, jsondata)  

  ForEach dat\choices()
    content$=dat\choices()\message\content
    Debug content$
  Next
          
  FreeJSON(hJSON)
EndIf

[SOLVED] Re: Fetching JSON value

Posted: Wed Aug 30, 2023 7:15 am
by Janni
wow you guys are great!
Love the module and also the structure approach. I can work with this.

Thank you very much Little John, Gérard and Paul :D

Re: Fetching JSON value

Posted: Thu Aug 31, 2023 1:57 am
by kenmo
Some people prefer the Structure method, but I like the module/includefile approach like Little John :D

You can also check out my JSON_helper.pbi here (just an includefile, not module)
https://github.com/kenmo-pb/includes/bl ... Helper.pbi

The equivalent of Little John's example would be:

Code: Select all

XIncludeFile "JSON_Helper.pbi"

Define jn.i, s$
   
jn = LoadJSON(#PB_Any, "MyJSONdata.json")
If jn = 0
   Debug "Error: Can't load JSON file."
   End
EndIf   

s$ = JSONStringFromPath( MainJSONObject(jn), "choices[0]/message/content" )
Debug s$