JSON as standard format in Rest API - Time & Space Complexity
When working with REST APIs, JSON is the common way to send and receive data. Understanding how processing JSON scales helps us build faster apps.
We want to know how the time to handle JSON changes as the data size grows.
Analyze the time complexity of the following code snippet.
// Example: Parsing JSON data from an API response
const jsonData = '{"users": [{"id": 1}, {"id": 2}, {"id": 3}]}';
const data = JSON.parse(jsonData);
for (const user of data.users) {
console.log(user.id);
}
This code parses a JSON string and loops through the users to print their IDs.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array of users after parsing JSON.
- How many times: Once for each user in the array.
As the number of users grows, the time to parse and loop grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 loops plus parsing |
| 100 | About 100 loops plus parsing |
| 1000 | About 1000 loops plus parsing |
Pattern observation: The time grows roughly in direct proportion to the number of users.
Time Complexity: O(n)
This means the time to process the JSON grows linearly with the number of items inside it.
[X] Wrong: "Parsing JSON is instant and does not depend on data size."
[OK] Correct: Parsing reads every character, so bigger JSON takes more time to process.
Knowing how JSON parsing and data traversal scale helps you explain API performance clearly and confidently.
"What if we used nested JSON objects instead of a flat array? How would the time complexity change?"