0% found this document useful (0 votes)
2 views12 pages

JSON ProblemSolving LogicalThinking

The document provides a comprehensive guide on problem-solving and logical thinking using JSON, covering various real-world scenarios from beginner to advanced levels. It outlines a 5-step framework for effectively tackling JSON-related problems, including understanding the problem, visualizing the structure, and testing edge cases. Additionally, it includes practical examples and solutions in JavaScript and Python for tasks such as data extraction, filtering, aggregation, and transformation of JSON data.

Uploaded by

antony
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views12 pages

JSON ProblemSolving LogicalThinking

The document provides a comprehensive guide on problem-solving and logical thinking using JSON, covering various real-world scenarios from beginner to advanced levels. It outlines a 5-step framework for effectively tackling JSON-related problems, including understanding the problem, visualizing the structure, and testing edge cases. Additionally, it includes practical examples and solutions in JavaScript and Python for tasks such as data extraction, filtering, aggregation, and transformation of JSON data.

Uploaded by

antony
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Problem Solving & Logical

Thinking
with JSON — Step-by-Step with Real Examples
Freshers to Advanced | JavaScript & Python

Introduction: Why JSON + Problem Solving?


In real-world software development, JSON is everywhere — REST APIs, config files,
databases, logs, and more. But just knowing JSON syntax is not enough. You need to think
logically to:

• Parse and extract specific data from deeply nested JSON


• Transform, filter, and aggregate JSON data
• Debug and fix broken or invalid JSON
• Design efficient JSON structures for complex systems
• Handle edge cases like missing keys, null values, and arrays

This document teaches you how to THINK through JSON problems before writing a single line
of code.

The 5-Step Problem Solving Framework for JSON


TIP: Always follow this framework before writing code — it saves hours of debugging.

1. UNDERSTAND the problem — What input do you have? What output is expected?
2. VISUALIZE the JSON structure — Draw or trace the nesting levels.
3. IDENTIFY the path — Which keys/indices lead to the target data?
4. WRITE the logic — Use loops, conditions, and recursion as needed.
5. TEST with edge cases — Null values, empty arrays, missing keys.

Problem 1: Extract a Specific Value from Nested JSON


LEVEL Beginner
Problem Statement
GIVEN: A student profile in JSON. Extract the student's city name.

INPUT JSON
{
"student": {
"id": "S101",
"name": "Ananya Krishnan",
"address": {
"street": "12, Gandhi Nagar",
"city": "Coimbatore",
"pin": 641001
}
}
}

Step-by-Step Thinking
6. The city is inside: student -> address -> city
7. We need to access 3 levels deep using dot notation
8. No loops needed — it is a direct path

JAVASCRIPT SOLUTION
const data = {
student: {
id: "S101", name: "Ananya Krishnan",
address: { street: "12, Gandhi Nagar", city: "Coimbatore", pin:
641001 }
}
};

// Access nested value using dot notation


const city = [Link];
[Link](city); // Output: Coimbatore

// Safe access using Optional Chaining (handles missing keys)


const pin = data?.student?.address?.pin;
[Link](pin); // Output: 641001

PYTHON SOLUTION
import json

json_str = '{"student":{"id":"S101","name":"Ananya Krishnan","address":


{"city":"Coimbatore","pin":641001}}}'
data = [Link](json_str)

# Access nested value


city = data["student"]["address"]["city"]
print(city) # Output: Coimbatore
# Safe access using .get() — returns None if key missing
pin = [Link]("student", {}).get("address", {}).get("pin")
print(pin) # Output: 641001

KEY LESSON: Use optional chaining (?.) in JS and .get() in Python to safely access nested
keys without crashing on missing data.

Problem 2: Filter Items from a JSON Array


LEVEL Beginner–Intermediate

Problem Statement
GIVEN: A product list. Return only products where price < 500 and inStock is true.

INPUT JSON
{
"products": [
{ "id": 1, "name": "Pen", "price": 20, "inStock": true },
{ "id": 2, "name": "Notebook", "price": 120, "inStock": true },
{ "id": 3, "name": "Laptop", "price": 55000,"inStock": false },
{ "id": 4, "name": "Eraser", "price": 10, "inStock": true },
{ "id": 5, "name": "Tablet", "price": 8000, "inStock": true }
]
}

Logical Thinking Process


9. We have an ARRAY of objects inside the key "products"
10. Each object has price and inStock fields
11. We need TWO conditions both true: price < 500 AND inStock === true
12. Use filter() in JS or list comprehension in Python

JAVASCRIPT SOLUTION
const data = { products: [
{ id:1, name:"Pen", price:20, inStock:true },
{ id:2, name:"Notebook", price:120, inStock:true },
{ id:3, name:"Laptop", price:55000, inStock:false },
{ id:4, name:"Eraser", price:10, inStock:true },
{ id:5, name:"Tablet", price:8000, inStock:true }
]};

const result = [Link](


p => [Link] < 500 && [Link] === true
);

[Link](result);
// Output: Pen, Notebook, Eraser (all under 500 and in stock)

PYTHON SOLUTION
data = { "products": [
{"id":1,"name":"Pen", "price":20, "inStock":True },
{"id":2,"name":"Notebook", "price":120, "inStock":True },
{"id":3,"name":"Laptop", "price":55000, "inStock":False},
{"id":4,"name":"Eraser", "price":10, "inStock":True },
{"id":5,"name":"Tablet", "price":8000, "inStock":True }
]}

result = [p for p in data["products"]


if p["price"] < 500 and p["inStock"]]

for p in result:
print(p["name"], "-", p["price"])
# Output: Pen-20, Notebook-120, Eraser-10

Problem 3: Calculate Total from JSON Array


LEVEL Intermediate

Problem Statement
GIVEN: An order JSON with multiple items. Calculate the total bill amount after applying
discounts.

INPUT JSON
{
"orderId": "ORD-501",
"items": [
{ "name": "Rice 5kg", "qty": 2, "price": 250, "discount": 10 },
{ "name": "Dal 1kg", "qty": 3, "price": 90, "discount": 5 },
{ "name": "Oil 1L", "qty": 1, "price": 180, "discount": 0 },
{ "name": "Sugar 1kg", "qty": 2, "price": 45, "discount": 0 }
]
}

Logical Thinking Process


13. For each item: itemTotal = qty x price
14. Apply discount: discountedTotal = itemTotal - (itemTotal x discount/100)
15. Sum all discounted totals to get grand total
16. Use reduce() in JS or sum() with comprehension in Python

JAVASCRIPT SOLUTION
const order = {
orderId: "ORD-501",
items: [
{ name:"Rice 5kg", qty:2, price:250, discount:10 },
{ name:"Dal 1kg", qty:3, price:90, discount:5 },
{ name:"Oil 1L", qty:1, price:180, discount:0 },
{ name:"Sugar 1kg", qty:2, price:45, discount:0 }
]
};

const total = [Link]((sum, item) => {


const itemTotal = [Link] * [Link];
const afterDiscount = itemTotal - (itemTotal * [Link] / 100);
return sum + afterDiscount;
}, 0);

[Link]("Total Bill: Rs.", [Link](2));


// Output: Total Bill: Rs. 1074.50

STEP-BY-STEP CALCULATION
Rice 5kg : 2 x 250 = 500 => after 10% discount = 450.00
Dal 1kg : 3 x 90 = 270 => after 5% discount = 256.50
Oil 1L : 1 x 180 = 180 => no discount = 180.00
Sugar 1kg : 2 x 45 = 90 => no discount = 90.00
─────────────────────────────────────────────────
GRAND TOTAL = 976.50

Problem 4: Group and Count — JSON Aggregation


LEVEL Intermediate–Advanced

Problem Statement
GIVEN: A list of employee records. Group employees by department and count how many are
in each department.

INPUT JSON
{
"employees": [
{ "id": 1, "name": "Suresh", "dept": "Engineering" },
{ "id": 2, "name": "Preethi", "dept": "HR" },
{ "id": 3, "name": "Vijay", "dept": "Engineering" },
{ "id": 4, "name": "Meena", "dept": "Finance" },
{ "id": 5, "name": "Arjun", "dept": "HR" },
{ "id": 6, "name": "Kavitha", "dept": "Engineering" }
]
}

Logical Thinking Process


17. Iterate through the employees array
18. For each employee, read the dept field
19. Use a result object/dict: if dept exists, increment count; else set to 1
20. This is the classic GROUP BY pattern

JAVASCRIPT SOLUTION
const data = { employees: [
{id:1,name:"Suresh", dept:"Engineering"},
{id:2,name:"Preethi",dept:"HR"},
{id:3,name:"Vijay", dept:"Engineering"},
{id:4,name:"Meena", dept:"Finance"},
{id:5,name:"Arjun", dept:"HR"},
{id:6,name:"Kavitha",dept:"Engineering"}
]};

const grouped = [Link]((acc, emp) => {


acc[[Link]] = (acc[[Link]] || 0) + 1;
return acc;
}, {});

[Link](grouped);
// Output: { Engineering: 3, HR: 2, Finance: 1 }

PYTHON SOLUTION
from collections import Counter

employees = [
{"id":1,"name":"Suresh", "dept":"Engineering"},
{"id":2,"name":"Preethi","dept":"HR"},
{"id":3,"name":"Vijay", "dept":"Engineering"},
{"id":4,"name":"Meena", "dept":"Finance"},
{"id":5,"name":"Arjun", "dept":"HR"},
{"id":6,"name":"Kavitha","dept":"Engineering"}
]

dept_count = Counter(e["dept"] for e in employees)


print(dict(dept_count))
# Output: {"Engineering": 3, "HR": 2, "Finance": 1}
Problem 5: Find & Validate — Search in Nested JSON
LEVEL Advanced

Problem Statement
GIVEN: A hospital JSON with doctors, their specializations, and available slots. Find all
available cardiologists with a slot on '2024-12-10'.

INPUT JSON
{
"hospital": "Apollo Medical Centre",
"doctors": [
{
"id": "D01", "name": "Dr. Ramesh",
"specialization": "Cardiology",
"slots": ["2024-12-10","2024-12-12","2024-12-15"]
},
{
"id": "D02", "name": "Dr. Nandha",
"specialization": "Neurology",
"slots": ["2024-12-10","2024-12-11"]
},
{
"id": "D03", "name": "Dr. Lalitha",
"specialization": "Cardiology",
"slots": ["2024-12-11","2024-12-14"]
},
{
"id": "D04", "name": "Dr. Senthil",
"specialization": "Cardiology",
"slots": ["2024-12-10","2024-12-13","2024-12-16"]
}
]
}

Logical Thinking Process


21. Filter doctors where specialization === "Cardiology"
22. For each cardiologist, check if slots array includes '2024-12-10'
23. Return matching doctors with their IDs and names
24. This combines filter on object field + search inside an array field

JAVASCRIPT SOLUTION
const targetDate = "2024-12-10";

const available = [Link](doc =>


[Link] === "Cardiology" &&
[Link](targetDate)
);

[Link](doc =>
[Link](`${[Link]} (${[Link]}) is available on ${targetDate}`)
);

// Output:
// Dr. Ramesh (D01) is available on 2024-12-10
// Dr. Senthil (D04) is available on 2024-12-10

PYTHON SOLUTION
target_date = "2024-12-10"

available = [
doc for doc in data["hospital"]["doctors"]
if doc["specialization"] == "Cardiology"
and target_date in doc["slots"]
]

for doc in available:


print(f'{doc["name"]} ({doc["id"]}) available on {target_date}')

# Output:
# Dr. Ramesh (D01) available on 2024-12-10
# Dr. Senthil (D04) available on 2024-12-10

Problem 6: Transform JSON Structure (Map &


Reshape)
LEVEL Advanced

Problem Statement
GIVEN: Raw API response with student marks. Transform it into a report-ready format that
shows only name, total, percentage, and grade.

INPUT JSON
{
"exam": "Class 12 Board",
"students": [
{ "id":"ST01","name":"Deepa", "marks":
{"Tamil":88,"English":92,"Maths":95,"Science":89,"Social":85} },
{ "id":"ST02","name":"Kiran", "marks":
{"Tamil":70,"English":75,"Maths":68,"Science":72,"Social":65} },
{ "id":"ST03","name":"Roshini","marks":
{"Tamil":95,"English":98,"Maths":100,"Science":97,"Social":96} }
]
}

Logical Thinking Process


25. For each student, extract all marks values and sum them
26. Percentage = (total / 500) x 100
27. Assign grade: A+ (>=90), A (>=75), B (>=60), C (below 60)
28. Use map() to transform each student object into a new shape

JAVASCRIPT SOLUTION
function getGrade(pct) {
if (pct >= 90) return "A+";
if (pct >= 75) return "A";
if (pct >= 60) return "B";
return "C";
}

const report = [Link](student => {


const total = [Link]([Link]).reduce((s,m) => s+m, 0);
const pct = (total / 500 * 100).toFixed(1);
const grade = getGrade(parseFloat(pct));
return { name: [Link], total, percentage: pct + "%", grade };
});

[Link]([Link](report, null, 2));

OUTPUT JSON
[
{ "name": "Deepa", "total": 449, "percentage": "89.8%", "grade": "A"
},
{ "name": "Kiran", "total": 350, "percentage": "70.0%", "grade": "B"
},
{ "name": "Roshini", "total": 486, "percentage": "97.2%", "grade": "A+"
}
]

Problem 7: Recursive Search in Deeply Nested JSON


LEVEL Expert

Problem Statement
GIVEN: A company org-chart in JSON (unlimited nesting). Find the employee with id 'E004'
anywhere in the tree.
INPUT JSON (Org Chart)
{
"id": "E001", "name": "CEO Rajan",
"reports": [
{ "id": "E002", "name": "VP Shanthi",
"reports": [
{ "id": "E004", "name": "Manager Karthik", "reports": [] },
{ "id": "E005", "name": "Manager Leela", "reports": [] }
]
},
{ "id": "E003", "name": "VP Guna", "reports": [] }
]
}

Logical Thinking — Recursion Pattern


29. Check if current node's id matches target
30. If yes, return the node
31. If no, recursively search each child in reports[]
32. If nothing found, return null

JAVASCRIPT — RECURSIVE SEARCH


function findEmployee(node, targetId) {
// Base case: found the target
if ([Link] === targetId) return node;

// Recursive case: search in all direct reports


for (const report of [Link]) {
const found = findEmployee(report, targetId);
if (found) return found; // return as soon as found
}

return null; // not found in this subtree


}

const result = findEmployee(orgChart, "E004");


[Link](result);
// Output: { id: "E004", name: "Manager Karthik", reports: [] }

PYTHON — RECURSIVE SEARCH


def find_employee(node, target_id):
# Base case
if node["id"] == target_id:
return node

# Recursive case
for report in [Link]("reports", []):
found = find_employee(report, target_id)
if found:
return found
return None

result = find_employee(org_chart, "E004")


print(result)
# Output: {"id": "E004", "name": "Manager Karthik", "reports": []}

Bonus: Debugging Logical Errors in JSON


Common JSON Logic Bugs and How to Fix Them

Bug Type Fix Strategy


Accessing missing key Use .get() in Python / optional chaining (?.) in JS
Off-by-one in array Remember arrays start at index 0, not 1
Wrong condition operator === checks value AND type in JS; use == in
Python
Mutating original data Use map/filter (they return new arrays, don't
modify original)
Summing string numbers Parse to int/float first: parseInt(), Number(), float()
Empty array crash Check [Link] > 0 before accessing [0]
Null reference error Always check for null/undefined before deep
access

Summary: Logical Thinking Patterns for JSON

Problem Type Pattern to Use


Extract nested value Follow the key path: obj.a.b.c — use optional
chaining
Filter from array Use filter() with your condition
Calculate totals Use reduce() — accumulate while iterating
Group & count Use reduce() into a {key: count} object
Search in array Use find() or filter() — check each element
Transform shape Use map() — return a new object per item
Deep nested search Use recursion — check node, then recurse into
children
Handle missing data Use .get() / ?. / default values / null checks

Think first. Code second. Test always.


— End of Problem Solving with JSON Notes —

You might also like