jQuery · Forms & AJAX

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.

Intermediate 5 min Lesson 15 of 22 Runnable examplesExamples use jQuery 3.x.
Before you start:AJAX
0/22 in jQuery
On this page · 5 min · Intermediate

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#

JavaScript Illustrative
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#

HTMLRendering an order from JSON Runnable
<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>
Expected output
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”.)
Opens this example in the full playground

Step-by-step explanation#

  1. JSON.parse turns the text into an object with a nested customer and an items array.
  2. reduce adds up price × qty for the total.
  3. ?? supplies a fallback for the null city.
  4. Every value is inserted with .text(), so the HTML in the name is displayed, not executed.
  5. 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#

Parsing twice

With dataType: "json", the data is already an object. JSON.parse(object) throws “Unexpected token o”.

Crashing on missing fields

order.customer.address.city throws if address is missing. Use ?. and ??.

Injecting data into HTML strings

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?
Parse, then map each item to $("<li>").text(...) with a ternary.
Show solution
HTML Runnable
<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>
Opens this example in the full playground

Mini quiz#

JSON Handling quizPredict the output Question 1 of 3

What is logged?

console.log(JSON.stringify({ a: 1, b: [2, 3] }));
Score so far: 0/0

Want more? Practise all jQuery MCQs · jQuery interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.