jQuery and JSON
JSON (JavaScript Object Notation) is the standard format for exchanging data with servers. It looks like JavaScript object literals, with a few strict rules: keys in double quotes, strings in double quotes, no trailing commas, no functions or comments.
{
"id": 42,
"name": "Espresso Beans",
"price": 24.5,
"tags": ["coffee", "beans"],
"inStock": true,
"supplier": null
}Converting JSON
JSON travels as text. JavaScript converts it with the built-in JSON object:
| Function | Converts |
|---|---|
JSON.parse(text) |
JSON string → JavaScript value (throws on invalid JSON) |
JSON.stringify(value) |
JavaScript value → JSON string |
JSON.stringify(value, null, 2) |
Same, pretty-printed with 2-space indentation |
Note: jQuery used to have
$.parseJSON(). It is deprecated since 3.0 and removed in jQuery 4 — useJSON.parse().
Receiving JSON
jQuery parses JSON responses for you when you use $.getJSON(), dataType: "json", or when the server sends Content-Type: application/json. Your callback then receives a ready-to-use object or array.
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; font-size: 14px; }
table { border-collapse: collapse; margin-top: 8px; }
th, td { border: 1px solid #ccc; padding: 4px 10px; }
th { background: #0769ad; color: #fff; cursor: pointer; }
td.num { text-align: right; }
.out { color: #c62828; }
</style>
</head>
<body>
<button id="load">Load products</button>
<table id="t"><thead><tr><th data-key="name">Name ⇅</th><th data-key="price">Price ⇅</th><th>Stock</th></tr></thead><tbody></tbody></table>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
const productsUrl = "data:application/json," + encodeURIComponent(JSON.stringify([
{ "name": "Espresso Beans", "price": 24.5, "stock": 12 },
{ "name": "Green Tea", "price": 9, "stock": 0 },
{ "name": "French Press", "price": 32, "stock": 4 },
{ "name": "Oat Milk", "price": 3.2, "stock": 40 }
]));
let products = [];
function render() {
$("#t tbody").empty().append($.map(products, p =>
$("<tr>").append(
$("<td>").text(p.name),
$("<td class='num'>").text("quot; + p.price.toFixed(2)),
$("<td>").text(p.stock > 0 ? p.stock : "sold out").toggleClass("out", p.stock === 0)
)));
}
$("#load").on("click", function () {
$.getJSON(productsUrl).done(function (data) {
console.log("type of data:", Array.isArray(data) ? "array" : typeof data, "| items:", data.length);
products = data;
render();
});
});
$("#t th[data-key]").on("click", function () {
const key = $(this).data("key");
products.sort((a, b) => a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0);
render();
console.log("sorted by", key);
});
</script>
</body>
</html>The table cells are filled with .text(), never by concatenating JSON values into an HTML string. Data from a server must be treated as untrusted text.
Sending JSON
By default jQuery sends data form-encoded (name=Ana&qty=2). Many APIs expect a JSON body instead. You must do two things:
- Turn the object into a string with
JSON.stringify. - Set
contentType: "application/json"so the server knows how to read it.
$.ajax({
url: "/api/orders",
method: "POST",
contentType: "application/json",
data: JSON.stringify({ items: [{ id: 17, qty: 2 }], coupon: null }),
dataType: "json"
}).done(order => console.log("order", order.id));| If you forget… | What the server receives |
|---|---|
JSON.stringify |
items%5B0%5D%5Bid%5D=17&… (form encoding of a nested object) |
contentType |
A JSON string labelled as form data — many frameworks ignore it |
Here is the difference made visible. The fake server echoes back the body and content type it received:
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif; font-size: 13px">
<button id="form">Send as form data</button>
<button id="json">Send as JSON</button>
<pre id="out" style="background:#f4f6f8;padding:8px;white-space:pre-wrap"></pre>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
// ---- fake echo server ----
$.ajaxTransport("+*", function (o) {
if (o.url !== "/api/echo") return;
return {
send(headers, complete) {
setTimeout(() => complete(200, "OK", {
text: JSON.stringify({ contentType: o.contentType, body: o.data })
}), 150);
},
abort() {}
};
});
// --------------------------
const order = { customer: "Ana", items: [{ id: 17, qty: 2 }] };
function send(asJson) {
$.ajax({
url: "/api/echo",
method: "POST",
dataType: "json",
contentType: asJson ? "application/json" : undefined,
data: asJson ? JSON.stringify(order) : order
}).done(function (echo) {
$("#out").text(JSON.stringify(echo, null, 2));
console.log(asJson ? "JSON" : "form", "body length:", echo.body.length);
});
}
$("#form").on("click", () => send(false));
$("#json").on("click", () => send(true));
</script>
</body>
</html>Handling bad JSON
If the server claims to send JSON but the text is invalid (an HTML error page, a stray comma), jQuery fails the request with textStatus === "parsererror":
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif; font-size: 14px">
<button id="go">Request broken JSON</button>
<p id="msg"></p>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
const broken = "data:application/json," + encodeURIComponent('{"name": "Ana",}'); // trailing comma!
$("#go").on("click", function () {
$.getJSON(broken)
.done(data => console.log("never happens", data))
.fail(function (xhr, textStatus, error) {
$("#msg").text("Could not read the server's answer.");
console.log("textStatus:", textStatus);
console.log("error:", error.name);
console.log("raw text:", xhr.responseText);
});
// the same check without AJAX
try {
JSON.parse('{"name": "Ana",}');
} catch (err) {
console.log("JSON.parse threw a", err.name);
}
});
</script>
</body>
</html>JSON helpers at a glance
| Task | Code |
|---|---|
| GET and parse | $.getJSON(url).done(data => …) |
| Force JSON parsing | $.ajax({ url, dataType: "json" }) |
| Send JSON | contentType: "application/json", data: JSON.stringify(obj) |
| Read an error body | xhr.responseJSON (when the error response was JSON) |
Store in localStorage |
localStorage.setItem("cart", JSON.stringify(cart)) |
| Data in HTML | <div data-config='{"a":1}'> → $("div").data("config").a |
Test yourself
Which is valid JSON?
{name: "Ana"}{'name': 'Ana'}{"name": "Ana"}{"name": "Ana",}
To POST a JSON body with $.ajax, you need…
dataType: "json"onlydata: JSON.stringify(obj)andcontentType: "application/json"processData: true$.parseJSON(obj)
A $.getJSON response contains invalid JSON. What happens?
donereceives the raw string- The request fails with textStatus
"parsererror" - jQuery fixes the JSON
- The page reloads