jquery-evnets

Parse JSON, XML and HTML – jQuery

In this post, find out jQuery code on how to parse JSON, parse XML and parse HTML. If you are still using custom code for parsing any of these and making your life more miserable then stop doing it. Why? If you are not aware then here is a news for you that jQuery has inbuilt utility methods for each. Which are,

  • parseJSON()
  • parseXML()
  • parseHTML()

Using parseJSON()

This method takes a well-formed JSON string and returns the resulting JavaScript object. It is available from jQuery 1.4.1 version.

$(document).ready(function() {
  var jsonp = '[{"Name":"Abc"},{"Name":"Xyz"}]';
  var sName = '';
  var obj = $.parseJSON(jsonp);
  $.each(obj, function() {
      sName += this['Name'] + "<br/>";
  });
  $('span').html(sName);
});​

Live Demo


Using parseXML()

This method parses a string into an XML document. $.parseXML uses the native parsing function of the browser to create a valid XML Document. It is available from jQuery 1.5 version.

$(document).ready(function() {
    var str= '<xml version='1.0'><name>jQuery By Example</name></xml>';
    var xmlDoc = $.parseXML(str);
    var $xml = $(xmlDoc);
    var $Name = $xml.find('name');
    $('span').html($Name);
});​

Live Demo


Using parseHTML()

This method parses a string into an array of DOM nodes. $.parseHTML uses a native DOM element creation function to convert the string to a set of DOM elements, which can then be inserted into the document. This method was added in jQuery version 1.8

$(document).ready(function () {
    var str = "Hello, <b>my blog name is</b> jQueryByExample."
    var sName = '';
    var sHTML = $.parseHTML(str);
    $.each(sHTML, function (i, el) {
        sName += el.nodeName + "<br/>";
        //el.nodeName = #text otherwise HTML tag name.
        //el.nodeValue = actual value of the node.
    });
    $('span').html(sName);
});

Live Demo

Feel free to contact me for any help related to jQuery, I will gladly help you.

Related Posts


2 thoughts on “Parse JSON, XML and HTML – jQuery

  1. fatloss

    Enormous concerns right here. I am just willing to view your write-up. Thank you a lot exactly what looking onward to call people. Are you going to remember to lower me a e-mail?

    Reply
  2. web design community

    I am not certain where you’re getting your information, however great topic. I must spend some time studying more or understanding more. Thank you for magnificent information I was searching for this info for my mission.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *


*