SyntaxStudy
Sign Up
jQuery jQuery $.parseJSON() and Data Utilities
jQuery Intermediate 5 min read

jQuery $.parseJSON() and Data Utilities

jQuery provides several utility functions for working with serialised data: $.parseJSON() (now largely superseded by native JSON.parse()), $.parseHTML() for safely converting strings to DOM nodes, $.parseXML() for XML documents, and $.param() for serialising objects to query strings.

$.parseHTML()

$.parseHTML(htmlString, context, keepScripts) converts an HTML string into an array of DOM nodes. By default it strips <script> tags to prevent XSS. Pass true as the third argument only when you have a trusted source and genuinely need to execute scripts.

$.param()

$.param(object) serialises a plain object or array of name/value pairs into a URL-encoded query string — the same format produced by a form's GET submission. It is particularly useful when you need to build URLs manually for AJAX or navigation.

  • $.parseHTML(str) — HTML string to DOM array (XSS-safe)
  • $.parseXML(str) — XML string to XML document
  • $.param(obj) — object to query string
  • JSON.parse(str) — preferred over deprecated $.parseJSON()
Example
// $.param — build a query string from an object
var params = $.param({
    category: 'books',
    page    : 2,
    sort    : 'price_asc'
});
console.log(params);
// "category=books&page=2&sort=price_asc"

// Use it in an AJAX URL
$.get('/api/products?' + params, function (data) {
    console.log(data);
});

// $.parseHTML — safely convert a string to DOM nodes
var nodes = $.parseHTML('<p>Safe <strong>content</strong></p>');
$('#output').append(nodes);

// JSON.parse (preferred over $.parseJSON)
var jsonStr = '{"name":"Alice","age":30}';
var obj = JSON.parse(jsonStr);
console.log(obj.name); // "Alice"

// $.parseXML
var xml = $.parseXML('<root><item>A</item><item>B</item></root>');
$(xml).find('item').each(function () {
    console.log($(this).text());
});
Pro Tip

Use $.parseHTML() instead of .html() or innerHTML when inserting user-influenced strings — it strips script tags by default.