JSON Handling
Almost every AJAX response is JSON. Turning it into a clean, safe page — and sending JSON back — is a core skill for jQuery developers.
On this page · 5 min · Intermediate
On this page
- Learning objectives
- Explanation
- Syntax
- Code example
- Step by step
- Real-world use
- Common mistakes
- Best practices
- Remember this
- Practice exercise
- Mini quiz
- Related topics
- My notes
- Reading time
- 5 min
- Difficulty
- Intermediate
- Updated
- Oct 28, 2026
Learning objectives#
- Parse and create JSON with JSON.parse and JSON.stringify
- Read nested objects and arrays from API data
- Render JSON into HTML safely
- Handle missing values and dates
Explanation#
JSON is text. JSON.parse(text) turns it into objects; JSON.stringify(obj) turns objects into text. With dataType: "json", jQuery parses responses for you.
Read nested data with dots and indexes: user.address.city, order.items[0].name. Use optional chaining (user.address?.city) and defaults (?? "–") for missing values.
Build HTML from data with jQuery elements and .text(), or with template literals that escape values. Never concatenate raw data into .html().
$.map(array, fn) or array.map(fn) transforms data; build all rows first and append once for speed.
Dates arrive as strings ("2026-10-28T09:30:00Z"). Convert with new Date(...) and format with toLocaleDateString().
Syntax#
const obj = JSON.parse('{"name":"Pen","price":20}');
const text = JSON.stringify({ name: 'Pen' }); // '{"name":"Pen"}'
const city = user.address?.city ?? 'Unknown';
Code example: Rendering an order from JSON#
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<div id="order" style="font-family:sans-serif"></div>
<script>
$(function () {
const json = '{"id":1042,"customer":{"name":"Asha <b>Rao</b>","city":null},' +
'"placedAt":"2026-10-28T09:30:00Z","items":[{"name":"Pen","price":20,"qty":3},{"name":"Notebook","price":60,"qty":1}]}';
const order = JSON.parse(json);
const total = order.items.reduce((sum, i) => sum + i.price * i.qty, 0);
const $box = $('#order');
$('<h3>').text('Order #' + order.id).appendTo($box);
$('<p>').text('Customer: ' + order.customer.name + ' (' + (order.customer.city ?? 'city not given') + ')').appendTo($box);
$('<p>').text('Placed: ' + new Date(order.placedAt).toISOString().slice(0, 10)).appendTo($box);
const $rows = order.items.map(i => $('<li>').text(i.qty + ' × ' + i.name + ' = ₹' + i.price * i.qty));
$('<ul>').append($rows).appendTo($box);
$('<p>').text('Total: ₹' + total).appendTo($box);
console.log('Items:', order.items.length, 'Total:', total);
console.log('Back to JSON:', JSON.stringify({ id: order.id, total }));
});
</script>
Items: 2 Total: 120
Back to JSON: {"id":1042,"total":120}
(The page shows “Order #1042”, the customer name with the <b> tags as plain text, “city not given”, the date 2026-10-28, two items and “Total: ₹120”.)Step-by-step explanation#
- JSON.parse turns the text into an object with a nested customer and an items array.
- reduce adds up price × qty for the total.
- ?? supplies a fallback for the null city.
- Every value is inserted with .text(), so the HTML in the name is displayed, not executed.
- All list items are built first and appended in one call.
Real-world use case#
An order-tracking page polls /api/orders/{id} every 30 seconds and re-renders the status timeline from the JSON response.
Common mistakes#
With dataType: "json", the data is already an object. JSON.parse(object) throws “Unexpected token o”.
order.customer.address.city throws if address is missing. Use ?. and ??.
Names and comments from users can contain markup. Use .text() or escape values.
Best practices#
- Let jQuery parse with dataType: "json"
- Guard nested reads with ?. and ??
- Render with .text()
- Build rows first, append once
Remember this#
parse = text → object. stringify = object → text.
a?.b ?? "default" for missing data.
JSON data → .text(), never raw .html().
Practice exercise#
Your task: Given the JSON string [{"name":"Pen","stock":0},{"name":"Bag","stock":4}], render a list where out-of-stock items show "(sold out)".
Need a hint?
Show solution
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<ul id="list"></ul>
<script>
$(function () {
const items = JSON.parse('[{"name":"Pen","stock":0},{"name":"Bag","stock":4}]');
$('#list').append(items.map(i => $('<li>').text(i.name + (i.stock === 0 ? ' (sold out)' : ''))));
console.log($('#list li').first().text()); // Pen (sold out)
});
</script>
Mini quiz#
What is logged?
console.log(JSON.stringify({ a: 1, b: [2, 3] }));
Want more? Practise all jQuery MCQs · jQuery interview questions
My notes#
Saved in this browser.