Home » Advanced » Handling JSON with jQuery

Handling JSON with jQuery

JSON (JavaScript Object Notation) is a solution to retailer info in an organized method. It’s the popular knowledge-interchange format as its shorter, light-weight, human-readable and requires no tags like XML. This enables quicker processing and transmission, and in addition the serializing and deserializing turns into a lot quicker when in comparison with XML. JSON returned by way of REST APIs is utilized in alternative ways on the shopper aspect. You’ll be able to populate knowledge in HTML parts, show the JSON on the UI after formatting and convert it to CSV for exporting. This submit supplies jQuery options for formatting the JSON, changing it to CSV format, and displaying the JSON knowledge in an HTML desk. Let’s start!

Format JSON in jQuery

Unformatted JSON just isn’t human-readable and more often than not the JSON returned by REST APIs will not be formatted, therefore can’t be displayed instantly on the UI. There are alternative ways to format it. Both utilizing your personal implementation or third-celebration plugins. Formatting the JSON utilizing jQuery may be carried out simply and requires solely 2 perform calls.

  1. JSON.parse() – To parse a JSON string and convert it to a JavaScript object.
  2. JSON.stringify() – Convert a JavaScript object right into a string. You can even apply indentation by passing an non-compulsory worth.

The next jQuery code codecs a JSON string:

var jData = '["fname":"Mark", "lname":"Wood", "company":"Apple",' +
'"fname":"Steve", "lname":"Jones", "company":"Amazon",' + 
'"fname":"Bill", "lname":"Peterson", "company":"HP",' +
'"fname":"Peter", "lname":"Jacobs", "company":"Dell"]';

var tmpData = JSON.parse(jData);
var formattedJson = JSON.stringify(tmpData, null, 't');

Right here, the formattedJson variable may have the formatted JSON string, indented utilizing tab. To show formatted JSON on UI, use the

 tag solely. If you wish to show inside a div, you would wish to first append the 
 tag within the div component. Like:

$('#dvText').append($('
').textual content(formattedJson));

You'll be able to take a look at the demo here.

Convert JSON to CSV

If you wish to convert JSON knowledge to CSV for export function, the next jQuery code will assist you. The next jQuery code defines a perform referred to as ConvertToCSV which takes JSON string, converts to CSV and returns it. Because it’s not obligatory to have comma as a delimiter for CSV, the delimiter is handed from outdoors which helps in altering the delimiter sooner or later with out altering the precise perform. The perform first converts the JSON knowledge into an array after which loops by way of the array to create a delimited string.

var jData = '["fname":"Mark", "lname":"Wood", "company":"Apple",' +
  '"fname":"Steve", "lname":"Jones", "company":"Amazon",' +
  '"fname":"Bill", "lname":"Peterson", "company":"HP",' +
  '"fname":"Peter", "lname":"Jacobs", "company":"Dell"]';

var seperator = ',';
var sCSV = ConvertToCSV(jData, seperator);

perform ConvertToCSV(jData, delimiter) 
  var arrJSON = typeof jData != 'object' ? JSON.parse(jData) : jData;
  var sReturnVal = '';
  for (var i = zero; i < arrJSON.size; i++) 
    var sLine = '';
    for (var index in arrJSON[i]) 
      if (sLine != '') sLine += delimiter;
      sLine += arrJSON[i][index];
    
    sReturnVal += sLine + 'rn';
  
  return sReturnVal;

You'll be able to take a look at the demo here.
The above perform simply creates a delimited string, it doesn’t help you reserve it as a .csv file. In the event you want to export/obtain the JSON knowledge right into a CSV file with column headings and an optionally available report title, the next jQuery code offers an answer for a similar. The modified perform now expects three extra parameters: report title, flag to show header, and a file identify. Whereas calling the perform, please contemplate following issues:

  • Should you don’t want to have a report title, move an empty string.
  • In case you don’t want a column header, move ShowHeader as false.
  • Move the file identify with out the .csv extension.

The perform does the next issues:

  • First, parses the JSON knowledge in an object, if not already.
  • If report title just isn't empty, appends the title to the variable.
  • If ShowHeader is true, then loop by way of the array’s 0th aspect to get the header columns after which appends them within the variable.
  • Then loop the array to get the info and creates a delimiter separated string.
  • As soon as the loop is accomplished, examine the variable for any errors. An empty worth means the JSON knowledge is just not right. In such a case, it logs the error and exits the perform.
  • If every little thing is right, then initialize file format. The file format is CSV on this case.
  • Then it creates a short lived anchor tag and appends it to the HTML physique with hidden visibility. Assigns the href and obtain attribute values and calls the anchor click on perform. Lastly, removes it once more from the physique because it’s not wanted.
perform ConvertToCSV(jData, title, ShowHeader, fileName, delimiter) 
  var arrJSON = typeof jData != 'object' ? JSON.parse(jData) : jData;
  var strCSV = '';
  //Set title first.
  if (title.size > zero)
    strCSV += title + 'rnn';
  if (ShowHeader) 
    var headerRow = "";
    for (var index in arrJSON[0]) 
      if (headerRow != '') headerRow += delimiter;
      headerRow += index;
    
    strCSV += headerRow + 'rn';
  
  for (var i = zero; i < arrJSON.size; i++) 
    var sLine = '';
    for (var index in arrJSON[i]) 
      if (sLine != '') sLine += delimiter;
      sLine += arrJSON[i][index];
    
    strCSV += sLine + 'rn';
  
  if (strCSV == '') 
    console.log('Error whereas changing resulting from invalid knowledge');
    return;
  
  var uri = 'knowledge:textual content/csv;charset=utf-eight,' + escape(strCSV);
  var hyperlink = doc.createElement("a");
  hyperlink.href = uri;
  hyperlink.fashion = "visibility:hidden";
  hyperlink.obtain = fileName + ".csv";
  $('physique').append(hyperlink);
  hyperlink.click on();
  $('physique').take away(hyperlink);

Name this perform on any occasion to transform the JSON knowledge right into a downloadable CSV file like:

ConvertToCSV(jData, "Worker Knowledge", true, "EmployeeReport", seperator);

You'll be able to take a look at the code in motion here.

Convert JSON to HTML Desk

The next jQuery code will create a desk factor, populates the desk knowledge from JSON knowledge and appends the desk aspect to the HTML physique. The perform makes use of jQuery syntax for various desk parts like header row and desk row. Contained in the JSON array loop, it appends the info in applicable objects, and eventually it's added to the HTML physique.

perform ConvertToTable(jData) 
  var arrJSON = typeof jData != 'object' ? JSON.parse(jData) : jData;
  var $desk = $('');
  var $headerTr = $('');

  for (var index in arrJSON[0]) 
    $headerTr.append($(' ').html(index));
  
  $desk.append($headerTr);
  for (var i = zero; i < arrJSON.size; i++) 
   var $tableTr = $('');
    for (var index in arrJSON[i]) 
      $tableTr.append($(' ').html(arrJSON[i][index]));
    
    $desk.append($tableTr);
  
  $('physique').append($desk);

Right here the desk formatting must be dealt with by way of CSS. You may as well incorporate the identical on this code with slight modifications.
You possibly can take a look at the code in motion here.

Conclusion

This publish supplies easy options for dealing with JSON on the shopper aspect in several methods. The jQuery implementation helps in formatting the unstructured JSON, changing the JSON knowledge right into a CSV string or downloadable CSV file with customization and displaying the JSON knowledge in an HTML desk. These jQuery codes aren't depending on any third-get together plugins, which lets you modify them as per your want with none problem.