Advanced Web Programming

JSON, XML and jQuery

PGCP-AC

Web applications exchange structured information and then present it through document interfaces. JSON and XML define two different data models, while jQuery provides a mature abstraction over DOM traversal, events, effects and network requests that remains important in existing applications.

1. Data interchange

JSON represents structured data using objects, arrays, strings, numbers, booleans and null. Object member names and string values use double quotes. Standard JSON does not contain comments, functions, undefined or trailing commas. JSON.parse turns JSON text into JavaScript values; JSON.stringify produces JSON text from suitable values. Serialization does not preserve all JavaScript behavior: prototype methods are not transferred as executable methods and cyclic object graphs require special treatment.

XML represents information with named elements and attributes. A well-formed XML document has properly nested tags and a single document element. XML is case-sensitive; namespaces distinguish names from different vocabularies. JSON is often convenient for web APIs, while XML remains useful when document structure, mixed content or established schemas matter. Neither format supplies application-level validation merely because it parses successfully.

2. jQuery operations

jQuery provides selector-based DOM access, event handling, traversal, manipulation, effects and AJAX helpers. $(selector) returns a jQuery collection, even when there is only one match. .eq(index) returns a jQuery collection containing the indexed item; .get(index) returns the underlying DOM element. .text() handles textual content, .html() handles markup, .val() reads or sets control values and .attr() works with attributes. Live boolean control state is ordinarily inspected with .prop().

const score = JSON.parse('{"team":"Blue","runs":42}');
$('#score').text(score.runs);
$('#links').on('click', 'a', function (event) {
  event.preventDefault();
  $(this).addClass('selected');
});

Traversal methods such as .parent(), .children() and .find() navigate relationships. Effects such as .hide(), .show() and .fadeOut() alter presentation. Plugins extend the library, but a plugin's behavior and dependencies must be understood separately. Data attributes attach small pieces of metadata to elements; they are not an appropriate store for secrets.

3. A small scoreboard document

{
  "team": "Blue",
  "innings": 1,
  "score": { "runs": 84, "wickets": 2 },
  "batters": ["Asha", "Neel"]
}

The document distinguishes numeric values from quoted text and nests related score properties. A client must still check that runs and wickets satisfy the application's rules; parsing proves syntactic validity, not cricket-specific validity. A JSON array preserves an element sequence, whereas object members should be accessed by their names rather than treated as a positional record.

For jQuery, .on('click', handler) attaches behavior, .off() removes selected handlers and .closest(selector) walks from an element toward its ancestors to find a match. .addClass() and .removeClass() keep styling in CSS. .offset() describes document-relative position; event pageX and pageY describe pointer coordinates relative to the document. Keep the chosen coordinate frame consistent when computing a relative position.

4. JSON syntax and data model

JSON has six kinds of value: object, array, string, number, boolean and null. Objects contain string-named members; arrays contain ordered values. Member names and strings require double quotation marks.

{
  "course": "PGCP-AC",
  "active": true,
  "modules": ["AWP", "DBT"],
  "result": null
}

Standard JSON excludes comments, functions, symbols, undefined, NaN, Infinity, trailing commas and single-quoted strings. JSON text is language-independent data, not executable JavaScript source. Never parse it with eval.

A syntactically valid document can still violate application rules. An order with a negative quantity parses successfully. Validation must separately check required members, types, ranges, relationships and authorization.

5. Parsing and serialization

function readSettings(text) {
  try {
    const value = JSON.parse(text);
    if (!value || typeof value !== 'object' || Array.isArray(value)) {
      throw new TypeError('Settings must be an object');
    }
    return value;
  } catch (error) {
    throw new Error('Invalid settings document', { cause: error });
  }
}

JSON.parse checks JSON grammar and creates ordinary JavaScript values. A reviver can transform values during parsing. JSON.stringify accepts an optional replacer and indentation argument.

Serialization has deliberate limits:

  • object properties whose value is undefined, a function or a symbol are omitted;
  • unsupported array entries become null-like placeholders;
  • NaN and infinities serialize as null;
  • dates ordinarily use their JSON string representation;
  • prototype methods and property descriptors are not preserved;
  • a reachable cycle normally causes an exception;
  • bigint values require an explicit representation policy.

JSON serialization is therefore not a universal object-cloning mechanism.

6. Designing JSON documents

Use stable, descriptive member names and consistent types. Distinguish absent, null, empty and zero according to the API contract. Arrays represent ordered sequences; objects represent named fields. Avoid positional arrays such as [17,"Asha",true] when { "id":17, "name":"Asha", "active":true } communicates the schema more clearly.

Version public representations deliberately. Producers should not silently change a number into a formatted string. Consumers should reject invalid critical fields and decide explicitly whether unknown members are tolerated.

7. XML structure and well-formedness

<?xml version="1.0" encoding="UTF-8"?>
<catalog xmlns="https://example.com/catalog">
  <book id="b17">
    <title>Web Data</title>
    <price currency="INR">450</price>
  </book>
</catalog>

A well-formed XML document has one document element, properly nested tags, quoted attribute values and case-matching start and end tags. Reserved characters need entity references or suitable character data handling. Comments and processing instructions are part of XML's document-oriented capabilities.

Elements can contain ordered mixed content, which is useful for document markup. Attributes are appropriate for compact metadata, but representing complex repeating structures as attribute strings makes processing difficult.

8. Namespaces, validation and XPath

Namespaces distinguish identically spelled names belonging to different vocabularies. A namespace prefix is a local shorthand; the namespace URI supplies the actual identity.

<doc xmlns:h="http://www.w3.org/1999/xhtml"
     xmlns:c="https://example.com/course">
  <h:p>Published course: <c:title>AWP</c:title></h:p>
</doc>

Well-formedness only establishes basic XML syntax. A DTD or XML Schema can describe permitted structure and values. Schema validity still does not prove every business rule.

XPath selects nodes using path expressions and predicates. Namespace-aware XPath requires the application to bind prefixes correctly; the prefix written in the source document is not itself the semantic identity.

9. JSON and XML compared

ConcernJSONXML
Basic modelObjects, arrays, primitive valuesElements, attributes, text, ordered document nodes
Web API convenienceDirect mapping to common program valuesRequires XML parsing and node processing
Mixed document contentAwkwardNatural
NamespacesNo built-in namespace systemBuilt-in namespace mechanism
Schema optionsJSON Schema and application validationDTD, XSD and application validation
CommentsNot in standard JSONSupported

Choose according to the contract and ecosystem rather than assuming one format is universally superior.

10. jQuery collections and DOM elements

$(selector) returns a jQuery collection, which may contain zero, one or many elements. It is not the same object as a raw DOM element.

const $items = $('.item');
const $first = $items.eq(0); // wrapped collection
const first = $items.get(0); // raw DOM element

Most jQuery methods operate on every element in the collection and return the collection, enabling chaining. Getter forms often read from the first match. Check length when absence matters.

11. Content, values, attributes and properties

MethodMain purpose
.text()Read or set textual content
.html()Read or set parsed HTML content
.val()Read or set form-control values
.attr()Read or set markup attributes
.prop()Read or set live DOM properties
.data()Associate or read data values through jQuery's data facilities

Use .prop('checked') for current checkbox state. The checked attribute describes default markup state and may not track later user interaction in the same way. As with native innerHTML, .html(untrustedValue) can create markup injection. Use .text() for untrusted text.

12. Traversal and manipulation

const $card = $('#courses').find('[data-id="17"]').closest('.course-card');
$card.addClass('is-selected').siblings().removeClass('is-selected');

.find() searches descendants; .children() limits the search to immediate children; .parent() returns the immediate parent; .parents() considers ancestors; .closest() starts at the current element and moves upward until it finds a match. Traversal direction is an important distinction.

Manipulation methods include .append(), .prepend(), .before(), .after(), .remove() and .empty(). Keep presentation in CSS by changing classes instead of repeatedly assigning many inline styles.

13. Events and delegation

$('#course-list').on('click.course', '[data-action="open"]', function (event) {
  event.preventDefault();
  $(this).closest('.course-card').toggleClass('is-open');
});

$('#course-list').off('.course');

The selector argument creates delegated handling for current and future descendants. In a regular callback, this is the matched element. Event namespaces such as .course make related cleanup more precise. Arrow callbacks do not provide jQuery's dynamic this; use event.currentTarget if an arrow is preferred.

14. Effects, coordinates and queues

Methods such as .hide(), .show(), .fadeIn(), .fadeOut() and .slideToggle() change presentation, often through an animation queue. Repeated triggers can build a queue and make the interface feel delayed; .stop() or state-based design may be appropriate.

.offset() reports document-relative position. .position() is relative to the offset parent. Pointer pageX and pageY are document-relative, while client coordinates are viewport-relative. Subtract values only when they use compatible coordinate systems.

Motion should respect user preferences and must not hide essential state. The final DOM state, focus behavior and accessible notification matter more than the visual effect.

15. AJAX helpers and error handling

Legacy code may use $.ajax, $.get or $.post:

$.ajax({ url: '/api/scores', method: 'GET', dataType: 'json' })
  .done(data => renderScore(data))
  .fail((xhr, status, error) => showError(`${status}: ${error}`));

dataType describes the expected response processing. Request content type is a different concern. Always handle loading, success, empty results, malformed data, HTTP failure and cancellation or superseded requests where applicable.

Modern applications often use Fetch and native DOM APIs, but a working jQuery codebase does not need automatic rewriting. Migration should reduce dependencies or improve maintainability with tests protecting existing behavior.

16. Security and maintainability

Data attributes and client-side objects are visible and modifiable by users; never treat them as secret or authoritative. Validate server responses before rendering, insert text safely and do not load untrusted plugins. Pin and update dependencies according to the project's maintenance policy.

Plugins add their own API, lifecycle, accessibility and cleanup rules. Verify compatibility with the installed jQuery version and avoid initializing the same element repeatedly without destruction.

17. Integrated example

function renderScoreboard(jsonText) {
  const data = JSON.parse(jsonText);
  if (!data.team || !Number.isInteger(data.score?.runs)) {
    throw new TypeError('Invalid scoreboard data');
  }

  const $board = $('#scoreboard').empty();
  $('<h2>').text(data.team).appendTo($board);
  $('<p>').text(`${data.score.runs}/${data.score.wickets}`).appendTo($board);
  const $list = $('<ul>').appendTo($board);
  data.batters.forEach(name => $('<li>').text(name).appendTo($list));
}

The function separates syntax parsing from domain validation, empties the old view deliberately, creates structure with trusted fixed markup and inserts external values as text.

18. Practical considerations

  1. JSON names and strings require double quotes.
  2. Parsing proves syntax, not domain validity.
  3. JSON cannot ordinarily represent cyclic references.
  4. XML is case-sensitive and needs one document element.
  5. Namespace identity comes from the URI, not merely a prefix spelling.
  6. .eq() returns a jQuery collection; .get() returns a DOM element.
  7. .prop('checked') reads live checkbox state.
  8. .find() descends; .closest() ascends starting at the current element.
  9. .html() parses markup and is unsafe for untrusted strings.
  10. Data attributes are inspectable and must not contain secrets.

Continue learning

Related notes

Put this topic into timed practice

Open mock tests when you want full-exam pacing, or keep drilling in practice mode.