Guide 1.7: Developer Guide

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.1

JSON 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.2

When 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, use JSON.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 json library and call json.loads(response) to convert it into a Python Dictionary.

Extracting Data

1.7.3

Once 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.4

Because 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.5

Occasionally, 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.

Want to test visually?

Next, learn how to use Postman to test endpoints without writing code.

Next Guide: Testing with Postman →
Avatar

How can we help?

We reply immediately

Hello! 👋 How can we help you today?