1

¿Como puedo encontrar "content" del json que manda chatGPT usando kotlin?.

Este es el Json que normalmente manda chatgpt

{
 'id': 'chatcmpl-6p9XYPYSTTRi0xEviKjjilqrWU2Ve',
 'object': 'chat.completion',
 'created': 1677649420,
 'model': 'gpt-3.5-turbo',
 'usage': {'prompt_tokens': 56, 'completion_tokens': 31, 'total_tokens': 87},
 'choices': [
   {
    'message': {
      'role': 'assistant',
      'content': 'The 2020 World Series was played in Arlington, Texas at the Globe Life Field, which was the new home stadium for the Texas Rangers.'},
    'finish_reason': 'stop',
    'index': 0
   }
  ]
}

Usando kotlin puedo llegar a message de esta manera

val jsonArray = jsObct.getJSONArray("choices")
val result = jsonArray.getJSONObject(0).getString("message")

pero necesito lo que hay en content

{ 'role': 'assistant', 'content': 'The 2020 World Series was played in Arlington, Texas at the Globe Life Field, which was the new home stadium for the Texas Rangers.'}

¿Alguien sabe que más necesito hacer para llegar a 'content'?, porque si al final de "getString" coloco un "get", puedo seguir avanzando pero solo es 1 carácter lo que muestra y no funciona.

Estuve buscando y encontré esta forma en la solución de otro post con un tema distinto.

for (i in 1..jsonArray.length()) {
     val jsonObject = jsonArray.getJSONObject(i)
     val id = jsonObject.getJSONObject("id").getString("videoId")

Pero tampoco funcionó, ¿Alguien sabe que más podría hacer?

1 respuesta 1

1

Recuerda siempre esto:

Si el .json inicia con { se considera como objeto Json.

Si el .json inicia con [ es considerado como Arreglo Json.

Ahora, si análisis tu JSON:

{
 'id': 'chatcmpl-6p9XYPYSTTRi0xEviKjjilqrWU2Ve',
 'object': 'chat.completion',
 'created': 1677649420,
 'model': 'gpt-3.5-turbo',
 'usage': {'prompt_tokens': 56, 'completion_tokens': 31, 'total_tokens': 87},
 'choices': [
   {
    'message': {
      'role': 'assistant',
      'content': 'The 2020 World Series was played in Arlington, Texas at the Globe Life Field, which was the new home stadium for the Texas Rangers.'},
    'finish_reason': 'stop',
    'index': 0
   }
  ]
}

para obtener "content", a partir de tu objeto, debes obtener el array 'choices', después el objeto 'message' y dentro de este objeto puedse obtener el valor de 'content'

//obtener el array 'choices'
val jsonArray = jsObct.getJSONArray("choices")
//obtener el objeto 'message' del primer objeto (indice 0) en el array
val messageObj = jsonArray.getJSONObject(0).getJSONObject("message")
//dentro del objeto 'message' obtiene el valor "content"
val valorContent = messageObj.getString("content")

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.