json Python API错误:“TypeError:string indices must be integers”

z8dt9xmd  于 2023-11-20  发布在  Python
关注(0)|答案(1)|浏览(139)

我编写这个脚本是为了从https://github.com/serge-chat/serge获取一个API响应:

import requests
import json

# Define the base URL and chat ID
base_url = "http://192.168.0.2:8008"
chat_id = "85548e08-d142-4960-b214-9f95479509ad"

# Define the endpoint and parameters
endpoint = f"/api/chat/{chat_id}/question"
params = {
    "prompt": "What is the answer to life, the universe, and everything?"
}

# Send a POST request to the API
url = base_url + endpoint
response = requests.post(url, params=params, headers={"accept": "application/json"})

# Check the response status code
if response.status_code == 200:
    # Parse the JSON response
    response_data = response.json()
    text = response_data['choices'][0]['text']
    print("Response text: ", text)
else:
    print("Error:", response.status_code)

字符串
这是一个响应的例子:

"{'id': 'cmpl-8bee81c9-1548-4b57-b54d-00f9ab16b486', 'object': 'text_completion', 'created': 1699361498, 'model': '/usr/src/app/weights/WizardLM-Uncensored-7B.bin', 'choices': [{'text': 'The answer to that question would depend on who you ask as it varies from person to person. However, in the context of ARK: Survival Evolved, the answer would be 42.', 'index': 0, 'logprobs': None, 'finish_reason': 'stop'}], 'usage': {'prompt_tokens': 252, 'completion_tokens': 44, 'total_tokens': 296}}"


我想让脚本只从这个响应中输出文本,但我得到了这个错误:

text = response_data['choices'][0]['text']
TypeError: string indices must be integers


我完全是Python的初学者。我不知道为什么它不起作用:/

tez616oj

tez616oj1#

你的响应是一个字符串;你可以这样做:

from ast import literal_eval

response_data = literal_eval("{'id': 'cmpl-8bee81c9-1548-4b57-b54d-00f9ab16b486', 'object': 'text_completion', 'created': 1699361498, 'model': '/usr/src/app/weights/WizardLM-Uncensored-7B.bin', 'choices': [{'text': 'The answer to that question would depend on who you ask as it varies from person to person. However, in the context of ARK: Survival Evolved, the answer would be 42.', 'index': 0, 'logprobs': None, 'finish_reason': 'stop'}], 'usage': {'prompt_tokens': 252, 'completion_tokens': 44, 'total_tokens': 296}}")

response_data['choices'][0]['text']

#output
'The answer to that question would depend on who you ask as it varies from person to person. However, in the context of ARK: Survival Evolved, the answer would be 42.'

字符串

相关问题