Working With JSON Responses
JSON (JavaScript Object Notation) is the universal language of web APIs. Once SdashAPI sends the data to your application, you need to parse it so your chosen programming language can understand and manipulate it.
What is JSON?
1.7.1JSON is simply a way of formatting data as plain text so it can easily travel over the internet. Even though it is based on JavaScript syntax, virtually every modern programming language has built-in tools to convert JSON text into native data structures (like arrays, objects, or dictionaries).
Parsing JSON
1.7.2When your application receives the response from SdashAPI, it arrives as a long string of text. You must decode it before you can extract the question or options. Here is how you do it in the most common languages:
- JavaScript: When using the Fetch API, simply call
response.json()to convert the text into a JavaScript Object. Or, useJSON.parse(stringData). - PHP: Use the built-in function
json_decode($response, true)to convert the JSON string into an associative array. - Python: Use the built-in
jsonlibrary and calljson.loads(response)to convert it into a Python Dictionary.
Extracting Data
1.7.3Once parsed, you can access the nested fields using dot notation (in JavaScript) or bracket notation (in PHP and Python).
// JavaScript Example const questionText = parsedData.data.question; const correctAnswer = parsedData.data.answer; // PHP Example $questionText = $parsedData['data']['question']; $correctAnswer = $parsedData['data']['answer'];
Iterating Through Options
1.7.4Because the options are returned as an object (e.g. {"a": "16", "b": "14"}), you cannot use a standard array map directly. In JavaScript, you can use Object.entries() or Object.keys() to convert the object into an iterable array.
// Generating HTML radio buttons dynamically
let html = '';
for (const [letter, text] of Object.entries(parsedData.data.option)) {
if (text !== null) {
html += `<label><input type="radio" value="${letter}"> ${text}</label>`;
}
}Handling Parsing Errors
1.7.5Occasionally, a network failure or a server-side crash could result in the API returning invalid JSON (or raw HTML). If you try to parse this invalid text, your application will throw an error and crash.
Always wrap your JSON parsing code in a try/catch block so your application can gracefully handle bad responses and show a friendly error message to the user instead of a blank screen.