Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I print a certain content of a decoded JSON?

Hello! I'm currently creating a game that interfaces with the OpenTDB that Tower Unite uses. In the development of this game, I go through and print some things to debug if needed. When I print the questions variable, it returns and prints correctly. It would print something along these lines:

{"response_code":0,"results":[{"category":"Entertainment: Video Games","type":"multiple","difficulty":"hard","question":"How long are all the cutscenes from Metal Gear Solid 4 (PS3, 2008) combined?","correct_answer":"8 hours","incorrect_answers":["4 hours","12 hours","5 hours"]}]}

This is normal. However, when I decode this in order to pick out things like the response_code to print, I get nil. Here's the code in question:

function generateQuestions()
	--Time to generate the questions!
	local questions = http:GetAsync("https://opentdb.com/api.php?amount="..amount.."&category="..categorynum, true)
	print(questions.result_code)
	local questionsNew = http:JSONDecode(questions)
	print(questionsNew.result_code)
	print(questions)
end

Which returns:

nil nil (insert random questions here)

What I need to do is get the results from the JSON, and then separate each question out to be displayed separately. But first, I need to get the certain results. Thanks!

1 answer

✓ Accepted answer

You're using result_code instead of response_code. This should work:

function generateQuestions()
    --Time to generate the questions!
    local questions = http:GetAsync("https://opentdb.com/api.php?amount="..amount.."&category="..categorynum, true)
    local questionsNew = http:JSONDecode(questions)
    print(questionsNew.response_code)
    print(questions)
end

I also removed your first print because it was before you decoded the JSON string.

This discussion is preserved as it was. New answers, comments, and votes are closed.