How to universally parse JSON into blocks using jQuery

In this article we are going to know how to universally parse JSON into blocks using jQuery.

In jQuery, to parse any data to any block is carried over by using DOM Insertion methods. Some of DOM Insertion methods are append(), appendTo(), html(), prepend(), prependTo(), text(). To parse JSON into any block is also handled in same way but along with Ajax callback functions and parse.JSON() methods. Here parse.JSON() methods is deprecated in jQuery 3.0, so JSON.parse() method used instead in later versions.

Syntax:

/* JSON data might be in array also */
var $json-data= '{json-index:json-values}'

/* Creating object for parsed JSON data */
var $json-object= JSON.parse($jsondata);

/* Parse text along with JSON data-value
 with respect to index */
$("selected block").text($json-object.index);
or

/* Parse HTML tag along with JSON data-value
 with respect to index */
$("selected block").html( "opentag" + $json-object.index + "closetag");
  • Parsing JSON string using native JSON.parse method.
  • JSON.parse method is used instead of jQuery 3.0’s deprecated method $.parseJSON().
<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="utf-8">
	<meta name="viewport"
		content="width=device-width,
				initial-scale=1">
	<script src="
https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
	</script>
	
	<style>
		div {
			border: 2px solid green;
			padding: 20px;
		}
		
		h2 {
			color: red;
		}
		
		b {
			color: #08f;
		}
	</style>
</head>

<body>
	<center>
		<h1 style="color:green;">
			GeeksforGeeeks
		</h1>
		<br>

		<div>
			<h2>Employee Details</h2>
			<p></p>
			<h2>Website Details</h2>
			<em></em>
		</div>
	</center>

	<script>
	
		// Using jQuery.parseJSON()
		var company = jQuery.parseJSON(
			'{"employee_name":"Adam","age":25,"salary":"11,500"}');
	
		$('p').html("<b>Employee Name:</b> " + company.employee_name
					+ ",<br><b>Age:</b> " + company.age +
					",<br> <b>Sal/Month:</b> " + company.salary);
	</script>
	
	<script>
		$(document).text(function() {
			var $mytxt = '{ "website":"GeeksforGeeeks",
			"url":"https://www.geeksforgeeks.org/" }'
			
			// Using JSON.parse()
			var $web = JSON.parse($mytxt);
			var $block = $('em');
			return $block.text("WebsiteName: " +
							$web.website +
							", URL: " + $web.url);
		});
	</script>
</body>

</html>

Leave a comment

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