Fetching JSON value

Just starting out? Need help? Post your questions and find answers here.
User avatar
Janni
Enthusiast
Enthusiast
Posts: 127
Joined: Mon Feb 21, 2022 5:58 pm
Location: Norway

Fetching JSON value

Post 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
Spec: Linux Mint 20.3 Cinnamon, i7-3770K, 16GB RAM, RTX 2070 Super
Little John
Addict
Addict
Posts: 4777
Joined: Thu Jun 07, 2007 3:25 pm
Location: Berlin, Germany

Re: Fetching JSON value

Post 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$
Gérard
User
User
Posts: 48
Joined: Sat Oct 17, 2015 6:00 pm
Location: France
Contact:

Re: Fetching JSON value

Post 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
■ 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
User avatar
Paul
PureBasic Expert
PureBasic Expert
Posts: 1282
Joined: Fri Apr 25, 2003 4:34 pm
Location: Canada
Contact:

Re: Fetching JSON value

Post 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
Image Image
User avatar
Janni
Enthusiast
Enthusiast
Posts: 127
Joined: Mon Feb 21, 2022 5:58 pm
Location: Norway

[SOLVED] Re: Fetching JSON value

Post 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
Spec: Linux Mint 20.3 Cinnamon, i7-3770K, 16GB RAM, RTX 2070 Super
User avatar
kenmo
Addict
Addict
Posts: 2033
Joined: Tue Dec 23, 2003 3:54 am

Re: Fetching JSON value

Post 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$
Post Reply