This is the new home of the egghelp.org community forum.
All data has been migrated (including user logins/passwords) to a new phpBB version.


For more information, see this announcement post. Click the X in the top right-corner of this box to dismiss this message.

extract json data

Help for those learning Tcl or writing their own scripts.
Post Reply
g
geek
Halfop
Posts: 47
Joined: Fri Oct 24, 2008 6:07 am

extract json data

Post by geek »

hi,
I need help to handle the result of a [::http::data $token]
I think the data is in json format
I get a "structure" like this:

Code: Select all

{"id":"cmpl-6oGBZmblablablablai9NTA","object":"text_completion","created":1677436637,"model":"text-davinci-003","choices":[{"text":"\n\nYes, today is Monday.","index":0,"logprobs":null,"finish_reason":null}],"usage":{"prompt_tokens":4,"completion_tokens":8,"total_tokens":12}}
and I want to extract the text field "\n\nYes, today is Monday."

how can I do?
User avatar
SpiKe^^
Owner
Posts: 831
Joined: Fri May 12, 2006 10:20 pm
Location: Tennessee, USA
Contact:

json=>list=>json fix?

Post by SpiKe^^ »

That json data is somewhat odd, keeping the easiest plans from working:)

Let us assume you have that data you posted above saved in a variable named $jsondata

I might use something like this...

Code: Select all

package require json

set jdict [::json::json2dict $jsondata]

set todaytext [dict get [lindex [dict get $jdict choices] 0] text]

The value I think you seek should be saved in $todaytext
SpiKe^^

Get BogusTrivia 2.06.4.7 at www.mytclscripts.com
or visit the New Tcl Acrhive at www.tclarchive.org
.
User avatar
caesar
Mint Rubber
Posts: 3778
Joined: Sun Oct 14, 2001 8:00 pm
Location: Mint Factory

Post by caesar »

Add a string map like:

Code: Select all

set todaytext [string map {\n {}} [dict get [lindex [dict get $jdict choices] 0] text]]
to remove the new lines.

Edit: Typo, it's string not strong map. :lol:
Last edited by caesar on Tue Feb 28, 2023 12:20 pm, edited 1 time in total.
Once the game is over, the king and the pawn go back in the same box.
g
geek
Halfop
Posts: 47
Joined: Fri Oct 24, 2008 6:07 am

Post by geek »

yes it works

thanks SpiKe^^ and caesar


I found a picture of how data is formatted:

Image
User avatar
caesar
Mint Rubber
Posts: 3778
Joined: Sun Oct 14, 2001 8:00 pm
Location: Mint Factory

Post by caesar »

You can use an online app like JSON Viewer as well. :)
Once the game is over, the king and the pawn go back in the same box.
g
geek
Halfop
Posts: 47
Joined: Fri Oct 24, 2008 6:07 am

Post by geek »

very useful

tnx
Post Reply