Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 7 years ago

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

Log in to vote
0
Answered by 7 years ago

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.

Ad

Answer this question