Quantcast
Channel: Advanced | Learning jQuery
Viewing all articles
Browse latest Browse all 12

Handling JSON with jQuery

$
0
0

JSON (JavaScript Object Notation) is a way to store information in an organized manner. It is the preferred data-interchange format as its shorter, lightweight, human-readable and requires no tags like XML. This allows faster processing and transmission, and also the serializing and deserializing becomes much faster when compared to XML. JSON returned via REST APIs is used in different ways on the client side. You can populate data in HTML elements, display the JSON on the UI after formatting and convert it to CSV for exporting. This post provides jQuery solutions for formatting the JSON, converting it to CSV format, and showing the JSON data in an HTML table. Let’s begin!

Format JSON in jQuery

Unformatted JSON is not human-readable and most of the time the JSON returned by REST APIs are not formatted, hence can’t be displayed directly on the UI. There are different ways to format it. Either using your own implementation or third-party plugins. Formatting the JSON using jQuery can be done easily and requires only 2 function calls.

  1. JSON.parse() - To parse a JSON string and convert it to a JavaScript object.
  2. JSON.stringify() - Convert a JavaScript object into a string. You can also apply indentation by passing an optional value.

The following jQuery code formats 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');

Here, the formattedJson variable will have the formatted JSON string, indented using tab. To display formatted JSON on UI, use the <pre> tag only. If you want to display inside a div, you would need to first append the <pre> tag in the div element. Like:

$('#dvText').append($('<pre>').text(formattedJson));

You can check out the demo here.

Convert JSON to CSV

If you want to convert JSON data to CSV for export purpose, the following jQuery code will help you. The following jQuery code defines a function called ConvertToCSV which takes JSON string, converts to CSV and returns it. Since it’s not compulsory to have comma as a delimiter for CSV, the delimiter is passed from outside which helps in changing the delimiter in the future without changing the actual function. The function first converts the JSON data into an array and then loops through 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);

function ConvertToCSV(jData, delimiter) {
  var arrJSON = typeof jData != 'object' ? JSON.parse(jData) : jData;
  var sReturnVal = '';
  for (var i = 0; i < arrJSON.length; i++) {
    var sLine = '';
    for (var index in arrJSON[i]) {
      if (sLine != '') sLine += delimiter;
      sLine += arrJSON[i][index];
    }
    sReturnVal += sLine + '\r\n';
  }
  return sReturnVal;
}

You can check out the demo here.
The above function just creates a delimited string, it doesn’t allow you to save it as a .csv file. If you wish to export/download the JSON data into a CSV file with column headings and an optional report title, the following jQuery code provides a solution for the same. The modified function now expects 3 more parameters: report title, flag to display header, and a file name. While calling the function, please consider following things:

  • If you don’t wish to have a report title, pass an empty string.
  • In case you don’t need a column header, pass ShowHeader as false.
  • Pass the file name without the .csv extension.

The function does the following things:

  • First, parses the JSON data in an object, if not already.
  • If report title is not empty, appends the title to the variable.
  • If ShowHeader is true, then loop through the array’s 0th element to get the header columns and then appends them in the variable.
  • Then loop the array to get the data and creates a delimiter separated string.
  • Once the loop is completed, check the variable for any errors. An empty value means the JSON data is not correct. In such a case, it logs the error and exits the function.
  • If everything is correct, then initialize file format. The file format is CSV in this case.
  • Then it creates a temporary anchor tag and appends it to the HTML body with hidden visibility. Assigns the href and download attribute values and calls the anchor click function. Finally, removes it again from the body as it’s no longer needed.
function ConvertToCSV(jData, title, ShowHeader, fileName, delimiter) {
  var arrJSON = typeof jData != 'object' ? JSON.parse(jData) : jData;
  var strCSV = '';
  //Set title first.
  if (title.length > 0)
    strCSV += title + '\r\n\n';
  if (ShowHeader) {
    var headerRow = "";
    for (var index in arrJSON[0]) {
      if (headerRow != '') headerRow += delimiter;
      headerRow += index;
    }
    strCSV += headerRow + '\r\n';
  }
  for (var i = 0; i < arrJSON.length; i++) {
    var sLine = '';
    for (var index in arrJSON[i]) {
      if (sLine != '') sLine += delimiter;
      sLine += arrJSON[i][index];
    }
    strCSV += sLine + '\r\n';
  }
  if (strCSV == '') {
    console.log('Error while converting due to invalid data');
    return;
  }
  var uri = 'data:text/csv;charset=utf-8,' + escape(strCSV);
  var link = document.createElement("a");
  link.href = uri;
  link.style = "visibility:hidden";
  link.download = fileName + ".csv";
  $('body').append(link);
  link.click();
  $('body').remove(link);
}

Call this function on any event to convert the JSON data into a downloadable CSV file like:

ConvertToCSV(jData, "Employee Data", true, "EmployeeReport", seperator);

You can check out the code in action here.

Convert JSON to HTML Table

The following jQuery code will create a table element, populates the table data from JSON data and appends the table element to the HTML body. The function uses jQuery syntax for different table elements like header row and table row. Inside the JSON array loop, it appends the data in appropriate objects, and finally it is added to the HTML body.

function ConvertToTable(jData) {
  var arrJSON = typeof jData != 'object' ? JSON.parse(jData) : jData;
  var $table = $('');
  var $headerTr = $('');

  for (var index in arrJSON[0]) {
    $headerTr.append($(' ').html(index));
  }
  $table.append($headerTr);
  for (var i = 0; i < arrJSON.length; i++) {
   var $tableTr = $('');
    for (var index in arrJSON[i]) {
      $tableTr.append($(' ').html(arrJSON[i][index]));
    }
    $table.append($tableTr);
  }
  $('body').append($table);
}

Here the table formatting needs to be handled via CSS. You can also incorporate the same in this code with slight modifications.
You can check out the code in action here.

Conclusion

This post provides simple solutions for handling JSON on the client side in different ways. The jQuery implementation helps in formatting the unstructured JSON, converting the JSON data into a CSV string or downloadable CSV file with customization and displaying the JSON data in an HTML table. These jQuery codes are not dependent on any third-party plugins, which helps you to modify them as per your need without any hassle.

The post Handling JSON with jQuery first appeared on Learning jQuery.


Viewing all articles
Browse latest Browse all 12

Latest Images

Trending Articles





Latest Images