<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Json &#8211; Sibeesh Passion</title>
	<atom:link href="https://mail.sibeeshpassion.com/tag/json/feed/" rel="self" type="application/rss+xml" />
	<link>https://mail.sibeeshpassion.com</link>
	<description>My passion towards life</description>
	<lastBuildDate>Wed, 02 Jun 2021 15:18:06 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>/wp-content/uploads/2017/04/Sibeesh_Passion_Logo_Small.png</url>
	<title>Json &#8211; Sibeesh Passion</title>
	<link>https://mail.sibeeshpassion.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Style Or Format JSON Data In JQuery</title>
		<link>https://mail.sibeeshpassion.com/style-or-format-json-data-in-jquery/</link>
					<comments>https://mail.sibeeshpassion.com/style-or-format-json-data-in-jquery/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Tue, 31 May 2016 00:00:34 +0000</pubDate>
				<category><![CDATA[How to]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[Format JSON]]></category>
		<category><![CDATA[How To]]></category>
		<category><![CDATA[Json]]></category>
		<category><![CDATA[JSON in Pre Tag]]></category>
		<category><![CDATA[Style JSON Data]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11648</guid>

					<description><![CDATA[In this post we will discuss how we can format or style the JSON you get from the server. Sometimes you may need to show the exact JSON you get from your API or from server in your web page. Normally if you just bind this JSON to any pre tag, it will look like just a straight line. Isn&#8217;t it? To overcome this we have an option in jQuery . I hope you will like this. Background For the past few months I am working with some Web API projects. As you all know the preferred output of an [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this post we will discuss how we can format or style the <a href="http://sibeeshpassion.com/tag/json/" target="_blank">JSON </a>you get from the server. Sometimes you may need to show the exact JSON you get from your API or from server in your web page. Normally if you just bind this JSON to any pre tag, it will look like just a straight line. Isn&#8217;t it? To overcome this we have an option in <a href="http://sibeeshpassion.com/category/jQuery/" target="_blank">jQuery </a>. I hope you will like this.</p>
<p><strong>Background</strong></p>
<p>For the past few months I am working with some <a href="http://sibeeshpassion.com/category/web-api/" target="_blank">Web API</a> projects. As you all know the preferred output of an API is JSON, I am returning JSON from my API. I wanted to show this JSON in a Pre tag as a result, but in a formatted way or stylish way. Here I am going to explain how we can do this. </p>
<p><strong>Using the code</strong></p>
<p>Before getting started, please make sure that you have added the jQuery reference to your page.</p>
<p>[html]<br />
 &lt;script src=&quot;scripts/jquery-2.2.3.js&quot;&gt;&lt;/script&gt;<br />
[/html]</p>
<p>Now let us say we are getting a JSON as follows from our API.</p>
<p>[js]<br />
[{&quot;AreaCode&quot;:&quot;B697-31&quot;,&quot;Revenue&quot;:12747128.190000001},{&quot;AreaCode&quot;:&quot;B697-92&quot;,&quot;Revenue&quot;:7922559.1600000048},{&quot;AreaCode&quot;:&quot;B697-76&quot;,&quot;Revenue&quot;:7541039.540000001},{&quot;AreaCode&quot;:&quot;B697-46&quot;,&quot;Revenue&quot;:7076495.5800000066},{&quot;AreaCode&quot;:&quot;B553-131&quot;,&quot;Revenue&quot;:5738816.5099999979},{&quot;AreaCode&quot;:&quot;B553-193&quot;,&quot;Revenue&quot;:4608556.52},{&quot;AreaCode&quot;:&quot;B697-74&quot;,&quot;Revenue&quot;:3895194.1099999994},{&quot;AreaCode&quot;:&quot;D158-233&quot;,&quot;Revenue&quot;:3572808.989999996},{&quot;AreaCode&quot;:&quot;B697-78&quot;,&quot;Revenue&quot;:3512657.6999999937},{&quot;AreaCode&quot;:&quot;B672-31&quot;,&quot;Revenue&quot;:2955916.9800000032},{&quot;AreaCode&quot;:&quot;B553-46&quot;,&quot;Revenue&quot;:2806813.7100000042}]<br />
[/js]</p>
<p>It will obviously looks like preceding when you just append it to a pre tag.</p>
<div id="attachment_11650" style="width: 526px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/JSON-in-Pre-Tag.png"><img fetchpriority="high" decoding="async" aria-describedby="caption-attachment-11650" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/JSON-in-Pre-Tag.png" alt="JSON in Pre Tag" width="516" height="115" class="size-full wp-image-11650" srcset="/wp-content/uploads/2016/05/JSON-in-Pre-Tag.png 516w, /wp-content/uploads/2016/05/JSON-in-Pre-Tag-300x67.png 300w, /wp-content/uploads/2016/05/JSON-in-Pre-Tag-400x89.png 400w" sizes="(max-width: 516px) 100vw, 516px" /></a><p id="caption-attachment-11650" class="wp-caption-text">JSON in Pre Tag</p></div>
<p>Now we will format this JSON string with JQuery Parse and JQuery stringify method as follows. </p>
<p>[js]<br />
  var tmpData = JSON.parse(data);<br />
                    var formattedData = JSON.stringify(tmpData, null, &#8216;\t&#8217;);<br />
                    $(&#8216;#output&#8217;).text(formattedData);<br />
[/js]</p>
<p>Here output is the id of our pre tag which we defined as follows.</p>
<p>[html]<br />
&lt;pre id=&quot;output&quot;&gt;&lt;/pre&gt;<br />
[/html]</p>
<p>Now if you bind the data after the formatting to pre tag, you will get an out put as follows. </p>
<div id="attachment_11651" style="width: 526px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/05/JSON-in-Pre-Tag-Output.png"><img decoding="async" aria-describedby="caption-attachment-11651" src="http://sibeeshpassion.com/wp-content/uploads/2016/05/JSON-in-Pre-Tag-Output.png" alt="JSON in Pre Tag Output" width="516" height="861" class="size-full wp-image-11651" srcset="/wp-content/uploads/2016/05/JSON-in-Pre-Tag-Output.png 516w, /wp-content/uploads/2016/05/JSON-in-Pre-Tag-Output-180x300.png 180w, /wp-content/uploads/2016/05/JSON-in-Pre-Tag-Output-400x667.png 400w, /wp-content/uploads/2016/05/JSON-in-Pre-Tag-Output-360x600.png 360w" sizes="(max-width: 516px) 100vw, 516px" /></a><p id="caption-attachment-11651" class="wp-caption-text">JSON in Pre Tag Output</p></div>
<p><strong>Conclusion</strong></p>
<p>Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn&#8217;t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/style-or-format-json-data-in-jquery/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Bind Json Data to JQWidget JQX Grid</title>
		<link>https://mail.sibeeshpassion.com/bind-json-data-to-jqwidget-jqx-grid/</link>
					<comments>https://mail.sibeeshpassion.com/bind-json-data-to-jqwidget-jqx-grid/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 18 Jun 2015 09:12:56 +0000</pubDate>
				<category><![CDATA[JQWidgets]]></category>
		<category><![CDATA[JQX Grid]]></category>
		<category><![CDATA[Products]]></category>
		<category><![CDATA[Bind JSON to Grid]]></category>
		<category><![CDATA[Json]]></category>
		<category><![CDATA[JSON Grid]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=5081</guid>

					<description><![CDATA[Introduction Hi All, How are you today? Today we will learn how we can bind a Json data to JQWidget, JQX Grid. I hope you will like it. Downloads Download the source files here: BindJSONToGrid.rar Background If you are new to JQWidget JQX Grid, Please find out here: http://sibeeshpassion.com/category/jqwidgets/ Using the code Here I am using Visual Studio 2012. We will have a txt file in which we will have the JSON data, you can use this file or you can manually load Json data from server side. So let us start First of all we must include the needed [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>Hi All, How are you today? Today we will learn how we can bind a Json data to JQWidget, JQX Grid. I hope you will like it.</p>
<p><strong>Downloads</strong></p>
<p>Download the source files here: <a href="http://sibeeshpassion.com/download/BindJSONToGrid.rar" target="_blank">BindJSONToGrid.rar</a></p>
<p><strong>Background</strong></p>
<p>If you are new to JQWidget JQX Grid, Please find out here: <a href="http://sibeeshpassion.com/category/jqwidgets/" target="_blank">http://sibeeshpassion.com/category/jqwidgets/</a></p>
<p><strong>Using the code</strong></p>
<p>Here I am using Visual Studio 2012. We will have a txt file in which we will have the JSON data, you can use this file or you can manually load Json data from server side.</p>
<p><strong>So let us start</strong></p>
<p>First of all we must include the needed files for the grid.</p>
<p>[html]<br />
 &lt;script src=&quot;jquery-1.9.1.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script type=&quot;text/javascript&quot; src=&quot;JQXItems/jqwidgets/jqxcore.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script type=&quot;text/javascript&quot; src=&quot;JQXItems/jqwidgets/jqxdata.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script type=&quot;text/javascript&quot; src=&quot;JQXItems/jqwidgets/jqxbuttons.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script type=&quot;text/javascript&quot; src=&quot;JQXItems/jqwidgets/jqxscrollbar.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script type=&quot;text/javascript&quot; src=&quot;JQXItems/jqwidgets/jqxlistbox.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script type=&quot;text/javascript&quot; src=&quot;JQXItems/jqwidgets/jqxdropdownlist.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script type=&quot;text/javascript&quot; src=&quot;JQXItems/jqwidgets/jqxmenu.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script type=&quot;text/javascript&quot; src=&quot;JQXItems/jqwidgets/jqxgrid.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script type=&quot;text/javascript&quot; src=&quot;JQXItems/jqwidgets/jqxgrid.filter.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script type=&quot;text/javascript&quot; src=&quot;JQXItems/jqwidgets/jqxgrid.sort.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script type=&quot;text/javascript&quot; src=&quot;JQXItems/jqwidgets/jqxgrid.selection.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script type=&quot;text/javascript&quot; src=&quot;JQXItems/jqwidgets/jqxgrid.pager.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script type=&quot;text/javascript&quot; src=&quot;JQXItems/jqwidgets/jqxgrid.columnsresize.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script type=&quot;text/javascript&quot; src=&quot;JQXItems/jqwidgets/jqxgrid.columnsreorder.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script type=&quot;text/javascript&quot; src=&quot;JQXItems/jqwidgets/jqxgrid.export.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script type=&quot;text/javascript&quot; src=&quot;JQXItems/jqwidgets/jqxdata.export.js&quot;&gt;&lt;/script&gt;<br />
    &lt;script type=&quot;text/javascript&quot; src=&quot;JQXItems/jqwidgets/jqxdatatable.js&quot;&gt;&lt;/script&gt;<br />
    &lt;link href=&quot;JQXItems/jqwidgets/styles/jqx.base.css&quot; rel=&quot;stylesheet&quot; /&gt;<br />
[/html]</p>
<p>No we can start the grid implementation. For that create a ready function and add the codes as follows.<br />
[js]</p>
<p> &lt;script type=&quot;text/javascript&quot;&gt;<br />
        $(document).ready(function () {<br />
            // prepare the data<br />
            var data =<br />
            {<br />
                datatype: &quot;json&quot;,<br />
                datafields: [{ &quot;name&quot;: &quot;AreaCode&quot;, &quot;type&quot;: &quot;string&quot; }, { &quot;name&quot;: &quot;Revenue&quot;, &quot;type&quot;: &quot;number&quot; }],<br />
                //id: &#8216;id&#8217;,<br />
                url: &quot;jsonData.txt&quot;<br />
            };<br />
            $(&quot;#jqxgrid&quot;).jqxGrid(<br />
                  {<br />
                      source: data,<br />
                      columns: [{ &quot;text&quot;: &quot;Area Code&quot;, &quot;dataField&quot;: &quot;AreaCode&quot;, &quot;cellsalign&quot;: &quot;left&quot;, &quot;cellsformat&quot;: &quot;d&quot; }, { &quot;text&quot;: &quot;Revenue&quot;, &quot;dataField&quot;: &quot;Revenue&quot;, &quot;cellsalign&quot;: &quot;right&quot;, &quot;cellsformat&quot;: &quot;c2&quot; }],<br />
  pageable: true,<br />
                      filterable: true,<br />
                      sortable: true<br />
                  });<br />
        });<br />
    &lt;/script&gt;</p>
<p>[/js]</p>
<p>Now what else we need? Yes, we need to create a div where we can render our grid.</p>
<p>[html]<br />
 &lt;h2&gt;Bind Json Data to JQwidgets JQX grid &#8211; Sibeesh Passion&lt;/h2&gt;<br />
    &lt;div id=&quot;jqxgrid&quot;&gt;&lt;/div&gt;<br />
[/html]</p>
<p>What about our data? We have not seen our data right? </p>
<p>[js]<br />
[{&quot;AreaCode&quot;:&quot;B697-31&quot;,&quot;Revenue&quot;:12747128.190000001},{&quot;AreaCode&quot;:&quot;B697-92&quot;,&quot;Revenue&quot;:7922559.1600000048},{&quot;AreaCode&quot;:&quot;B697-76&quot;,&quot;Revenue&quot;:7541039.540000001},{&quot;AreaCode&quot;:&quot;B697-46&quot;,&quot;Revenue&quot;:7076495.5800000066},{&quot;AreaCode&quot;:&quot;B553-131&quot;,&quot;Revenue&quot;:5738816.5099999979},{&quot;AreaCode&quot;:&quot;B553-193&quot;,&quot;Revenue&quot;:4608556.52},{&quot;AreaCode&quot;:&quot;B697-74&quot;,&quot;Revenue&quot;:3895194.1099999994},{&quot;AreaCode&quot;:&quot;D158-233&quot;,&quot;Revenue&quot;:3572808.989999996},{&quot;AreaCode&quot;:&quot;B697-78&quot;,&quot;Revenue&quot;:3512657.6999999937},{&quot;AreaCode&quot;:&quot;B672-31&quot;,&quot;Revenue&quot;:2955916.9800000032},{&quot;AreaCode&quot;:&quot;B553-46&quot;,&quot;Revenue&quot;:2806813.7100000042}]<br />
[/js]</p>
<p>All set now. So shall we see the grid now?</p>
<p><strong>Output</strong></p>
<p><img decoding="async" src="http://sibeeshpassion.com/content/images/bndjsn1.PNG" alt="" /></p>
<p><strong>Things to remember</strong></p>
<p>Make sure that your  data type is json in source object.</p>
<p>[js]<br />
datatype: &quot;json&quot;<br />
[/js]</p>
<p>Make sure your json is valid</p>
<p><strong>Conclusion</strong></p>
<p>I hope you will like this article. Please share me your valuable thoughts and comments. Your feedback is always welcomed.</p>
<p>Thanks in advance. Happy coding!</p>
<p>Kindest Regards<br />
<a href="https://plus.google.com/+sibeeshkv" target="_blank">Sibeesh Venu</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/bind-json-data-to-jqwidget-jqx-grid/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Sort a JSON Array Programmatically by a Property</title>
		<link>https://mail.sibeeshpassion.com/sort-a-json-array-programmatically-by-a-property/</link>
					<comments>https://mail.sibeeshpassion.com/sort-a-json-array-programmatically-by-a-property/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Wed, 10 Jun 2015 00:00:47 +0000</pubDate>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[Json]]></category>
		<category><![CDATA[Json Array]]></category>
		<category><![CDATA[Sort]]></category>
		<category><![CDATA[Sort array by property]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=2141</guid>

					<description><![CDATA[Introduction Hi all, I hope you all are fine. Today we will learn how to sort a JSON object by its property. We will be using normal jQuery features to do this. I hope you will like it. Background Yesterday I got a situation where I needed to sort my JSON object that I am creating using server data. So I though of sharing that with you all. Using the code First of all we will add a jQuery reference as in the following: [js] &#60;script src=“jquery-2.1.4.min.js”&#62;&#60;/script&#62; [/js] Now we need some, data right? Please have a look at the [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>Hi all, I hope you all are fine. Today we will learn how to sort a JSON object by its property. We will be using normal jQuery features to do this. I hope you will like it.</p>
<p><strong>Background</strong></p>
<p>Yesterday I got a situation where I needed to sort my JSON object that I am creating using server data. So I though of sharing that with you all.</p>
<p><strong>Using the code</strong></p>
<p>First of all we will add a jQuery reference as in the following:<br />
[js]<br />
&lt;script src=“jquery-2.1.4.min.js”&gt;&lt;/script&gt;<br />
[/js]</p>
<p>Now we need some, data right? Please have a look at the following JSON data.</p>
<p>[js]<br />
var data = ‘[{“name”:2014,”data”:[{“x”:”1″,”y”:222808746.81}]},{“name”:2013,”data”:[{“x”:”2″,”y”:289647045.18}]},{“name”:2014,”data”:[{“x”:”2″,”y”:285136890.07}]},{“name”:2013,”data”:[{“x”:”3″,”y”:370853178.74}]},{“name”:2014,”data”:[{“x”:”3″,”y”:403272964.28}]},{“name”:2012,”data”:[{“x”:”4″,”y”:217294031.36}]},{“name”:2013,”data”:[{“x”:”4″,”y”:224715039.94}]},{“name”:2014,”data”:[{“x”:”4″,”y”:249034460.23}]},{“name”:2012,”data”:[{“x”:”5″,”y”:215978054.15}]},{“name”:2013,”data”:[{“x”:”5″,”y”:241211810.92}]}]’;<br />
[/js]</p>
<p>Next we need some UI elements. Am I right?<br />
[html]<br />
&lt;div id=“unsorted”&gt;&lt;/div&gt;<br />
    &lt;div id=“sorted”&gt;&lt;/div&gt;<br />
    &lt;button id=“makemesort”&gt;Make Me Sort&lt;/button&gt;<br />
[/html]</p>
<p>What next?  We need to show this data to our UI, right? For that I am calling a function in our document ready function.<br />
[js]<br />
var jsonObject;<br />
        $(function () {<br />
            $(‘#sorted’).hide();<br />
            loadUnsorted();<br />
            $(‘#makemesort’).click(function () {<br />
                loadSorted();<br />
                $(‘#makemesort’).hide();<br />
                $(‘#sorted’).show();<br />
            });<br />
        });<br />
[/js]</p>
<p>The following is the function definition for the loadUnsorted() function.<br />
[js]<br />
function loadUnsorted() {<br />
           jsonObject = $.parseJSON(data);<br />
           var html = ‘&lt;table&gt;&lt;th&gt;Year&lt;/th&gt;&lt;th&gt;X Value&lt;/th&gt;&lt;th&gt;Y Value&lt;/th&gt;’;<br />
           for (i = 0; i &lt; jsonObject.length; i++) {<br />
               html += ‘&lt;tr&gt;&lt;td&gt;’ + jsonObject[i].name + ‘&lt;/td&gt;&lt;td&gt;’ + jsonObject[i].data[0].x + ‘&lt;/td&gt;&lt;td&gt;’ + jsonObject[i].data[0].y + ‘&lt;/td&gt;&lt;/tr&gt;’;<br />
           }<br />
           html += ‘&lt;/table&gt;’;<br />
           $(‘#unsorted’).append(html);<br />
       }<br />
[/js]</p>
<p>What we are doing here is parsing our data and appending the data to our UI element using a for loop.</p>
<p>Now if you run it, you will get output as follows.</p>
<p><img decoding="async" src="http://www.c-sharpcorner.com/UploadFile/65794e/sort-a-json-array-by-a-property-programatically/Images/srtjsn1.PNG" alt="" /></p>
<p>Now we have successfully formatted our data and shown it to our UI.  Cool, right?<br />
So shall we go and sort our data? I guess you said “Yes”. Awesome.<br />
Now we will create a click event for our “Make me sort” button as in the following:<br />
[js]<br />
$(‘#makemesort’).click(function () {<br />
                loadSorted();<br />
                $(‘#makemesort’).hide();<br />
                $(‘#sorted’).show();<br />
            });<br />
[/js]</p>
<p>So here is the definition for the loadSorted() function.<br />
[js]<br />
function loadSorted() {<br />
           jsonObject.sort(SortMe);<br />
           var html = ‘&lt;table&gt;&lt;th&gt;Year&lt;/th&gt;&lt;th&gt;X Value&lt;/th&gt;&lt;th&gt;Y Value&lt;/th&gt;’;<br />
           for (i = 0; i &lt; jsonObject.length; i++) {<br />
               html += ‘&lt;tr&gt;&lt;td&gt;’ + jsonObject[i].name + ‘&lt;/td&gt;&lt;td&gt;’ + jsonObject[i].data[0].x + ‘&lt;/td&gt;&lt;td&gt;’ + jsonObject[i].data[0].y + ‘&lt;/td&gt;&lt;/tr&gt;’;<br />
           }<br />
           html += ‘&lt;/table&gt;’;<br />
           $(‘#sorted’).append(html);<br />
       }<br />
[/js]</p>
<p>Now I guess you could determine the difference of both the loadSorted() and loadUnsorted() functions. Yeah, you are right. I am calling a sort function “sortMe”  there.<br />
[js]<br />
function SortMe(a, b) {<br />
           if (b.name != null &amp;&amp; b.name != undefined &amp;&amp; a.name != null &amp;&amp; a.name != undefined) {<br />
               var First = a.name.toString().toLowerCase();<br />
               var Second = b.name.toString().toLowerCase();<br />
               return ((First &lt; Second) ? -1 : ((First &gt; Second) ? 1 : 0));<br />
           }<br />
       }<br />
[/js]</p>
<p>What our “sortMe” function does is, it will take two objects at a time and compare those by the property “name” of each object.</p>
<p>[js]<br />
(First &lt; Second) ? -1 : ((First &gt; Second) ? 1 : 0)<br />
[/js]</p>
<p>Now shall we look into the complete code? We have done everything folks.</p>
<p><strong>Complete Code</strong></p>
<p>[html]<br />
&lt;!DOCTYPE html&gt;<br />
&lt;html&gt;<br />
&lt;head&gt;<br />
    &lt;title&gt;Sort JSON Object by its property and show demo – Sibeesh Passion&lt;/title&gt;<br />
    &lt;script src=“jquery-2.1.4.min.js”&gt;&lt;/script&gt;<br />
    &lt;style&gt;<br />
        #unsorted {<br />
            border: 1px solid #999;<br />
            width:220px;<br />
            padding:10px;<br />
            float:left;<br />
        }<br />
        #sorted {<br />
            border: 1px solid #999;<br />
            width:220px;<br />
            padding:10px;<br />
            float:left;<br />
        }<br />
         td {<br />
            border: 1px solid #ccc;<br />
            padding: 5px;<br />
            text-align: center;<br />
        }<br />
    &lt;/style&gt;<br />
    &lt;script&gt;<br />
        var data = ‘[{“name”:2014,”data”:[{“x”:”1″,”y”:222808746.81}]},{“name”:2013,”data”:[{“x”:”2″,”y”:289647045.18}]},{“name”:2014,”data”:[{“x”:”2″,”y”:285136890.07}]},{“name”:2013,”data”:[{“x”:”3″,”y”:370853178.74}]},{“name”:2014,”data”:[{“x”:”3″,”y”:403272964.28}]},{“name”:2012,”data”:[{“x”:”4″,”y”:217294031.36}]},{“name”:2013,”data”:[{“x”:”4″,”y”:224715039.94}]},{“name”:2014,”data”:[{“x”:”4″,”y”:249034460.23}]},{“name”:2012,”data”:[{“x”:”5″,”y”:215978054.15}]},{“name”:2013,”data”:[{“x”:”5″,”y”:241211810.92}]}]’;<br />
        var jsonObject;<br />
        $(function () {<br />
            $(‘#sorted’).hide();<br />
            loadUnsorted();<br />
            $(‘#makemesort’).click(function () {<br />
                loadSorted();<br />
                $(‘#makemesort’).hide();<br />
                $(‘#sorted’).show();<br />
            });<br />
        });<br />
        function loadUnsorted() {<br />
            jsonObject = $.parseJSON(data);<br />
            var html = ‘&lt;table&gt;&lt;th&gt;Year&lt;/th&gt;&lt;th&gt;X Value&lt;/th&gt;&lt;th&gt;Y Value&lt;/th&gt;’;<br />
            for (i = 0; i &lt; jsonObject.length; i++) {<br />
                html += ‘&lt;tr&gt;&lt;td&gt;’ + jsonObject[i].name + ‘&lt;/td&gt;&lt;td&gt;’ + jsonObject[i].data[0].x + ‘&lt;/td&gt;&lt;td&gt;’ + jsonObject[i].data[0].y + ‘&lt;/td&gt;&lt;/tr&gt;’;<br />
            }<br />
            html += ‘&lt;/table&gt;’;<br />
            $(‘#unsorted’).append(html);<br />
        }<br />
        function loadSorted() {<br />
            jsonObject.sort(SortMe);<br />
            var html = ‘&lt;table&gt;&lt;th&gt;Year&lt;/th&gt;&lt;th&gt;X Value&lt;/th&gt;&lt;th&gt;Y Value&lt;/th&gt;’;<br />
            for (i = 0; i &lt; jsonObject.length; i++) {<br />
                html += ‘&lt;tr&gt;&lt;td&gt;’ + jsonObject[i].name + ‘&lt;/td&gt;&lt;td&gt;’ + jsonObject[i].data[0].x + ‘&lt;/td&gt;&lt;td&gt;’ + jsonObject[i].data[0].y + ‘&lt;/td&gt;&lt;/tr&gt;’;<br />
            }<br />
            html += ‘&lt;/table&gt;’;<br />
            $(‘#sorted’).append(html);<br />
        }<br />
        function SortMe(a, b) {<br />
            if (b.name != null &amp;&amp; b.name != undefined &amp;&amp; a.name != null &amp;&amp; a.name != undefined) {<br />
                var First = a.name.toString().toLowerCase();<br />
                var Second = b.name.toString().toLowerCase();<br />
                return ((First &lt; Second) ? -1 : ((First &gt; Second) ? 1 : 0));<br />
            }<br />
        }<br />
    &lt;/script&gt;<br />
&lt;/head&gt;<br />
&lt;body&gt;<br />
    &lt;div id=“unsorted”&gt;&lt;/div&gt;<br />
    &lt;div id=“sorted”&gt;&lt;/div&gt;<br />
    &lt;button id=“makemesort”&gt;Make Me Sort&lt;/button&gt;<br />
&lt;/body&gt;<br />
&lt;/html&gt;<br />
[/html]</p>
<p>So now it is time to see our output. I am eager to see it.</p>
<p><img decoding="async" src="http://www.c-sharpcorner.com/UploadFile/65794e/sort-a-json-array-by-a-property-programatically/Images/srtjsn2.PNG" alt="" /></p>
<p>You can find we have sorted our object and shown it in a separate table. Cool.<br />
That is all for the day. I will return with another article soon.</p>
<p><strong>Conclusion</strong></p>
<p>I hope you liked this article. Please share me your valuable thoughts and comments. Your feedbacks are always welcome. Thanks in advance. Happy coding!.</p>
<p>Kindest Regards.<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/sort-a-json-array-programmatically-by-a-property/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Find JSON Objects With Same Property and Separate Them</title>
		<link>https://mail.sibeeshpassion.com/find-json-objects-with-same-property-and-separate-them/</link>
					<comments>https://mail.sibeeshpassion.com/find-json-objects-with-same-property-and-separate-them/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Fri, 29 May 2015 20:53:03 +0000</pubDate>
				<category><![CDATA[JQuery]]></category>
		<category><![CDATA[Json]]></category>
		<category><![CDATA[JSON Object]]></category>
		<category><![CDATA[Object By Property]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=2171</guid>

					<description><![CDATA[Introduction Today, this article explains how to find the objects with the same property from a JSON and separate them to be shown in the UI. I hope you will like it. Background Yesterday I came across a situation where there was a need to find the objects with the same property from some JSON data and separate them. So I thought of sharing that with you all. Using the code First of all we will add a jQuery reference as in the following code snippet: [js] &#60;script src=“jquery-2.1.4.min.js”&#62;&#60;/script&#62; [/js] Now we need some data, right? Please have a look [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>Today, this article explains how to find the objects with the same property from a JSON and separate them to be shown in the UI. I hope you will like it.</p>
<p><strong>Background</strong></p>
<p>Yesterday I came across a situation where there was a need to find the objects with the same property from some JSON data and separate them. So I thought of sharing that with you all.</p>
<p><strong>Using the code</strong></p>
<p>First of all we will add a jQuery reference as in the following code snippet:</p>
<p>[js]<br />
&lt;script src=“jquery-2.1.4.min.js”&gt;&lt;/script&gt;<br />
[/js]</p>
<p>Now we need some data, right? Please have a look at the following JSON data.</p>
<p>[js]<br />
var data = ‘[{“name”:2014,”data”:[{“x”:”1″,”y”:222808746.81}]},{“name”:2013,”data”:[{“x”:”2″,”y”:289647045.18}]},{“name”:2014,”data”:[{“x”:”2″,”y”:285136890.07}]},{“name”:2013,”data”:[{“x”:”3″,”y”:370853178.74}]},{“name”:2014,”data”:[{“x”:”3″,”y”:403272964.28}]},{“name”:2012,”data”:[{“x”:”4″,”y”:217294031.36}]},{“name”:2013,”data”:[{“x”:”4″,”y”:224715039.94}]},{“name”:2014,”data”:[{“x”:”4″,”y”:249034460.23}]},{“name”:2012,”data”:[{“x”:”5″,”y”:215978054.15}]},{“name”:2013,”data”:[{“x”:”5″,”y”:241211810.92}]},{“name”:2014,”data”:[{“x”:”5″,”y”:245950715.8}]},{“name”:2012,”data”:[{“x”:”6″,”y”:262898180.85}]},{“name”:2013,”data”:[{“x”:”6″,”y”:280550623.51}]},{“name”:2014,”data”:[{“x”:”6″,”y”:295780079.03}]},{“name”:2012,”data”:[{“x”:”7″,”y”:217310275.85}]},{“name”:2013,”data”:[{“x”:”7″,”y”:230973675.47}]},{“name”:2014,”data”:[{“x”:”7″,”y”:238227382.03}]}]’;<br />
[/js]</p>
<p>Next we need some UI elements as in the following:</p>
<p>[html]<br />
&lt;div id=“initialData”&gt;&lt;/div&gt;<br />
   &lt;div id=“newData”&gt;&lt;/div&gt;<br />
   &lt;button id=“separateme”&gt;Make Me Separate&lt;/button&gt;<br />
[/html]</p>
<p>What next? We need to show this data to our UI, right? For that I am calling a function in our document ready function.</p>
<p>[js]<br />
$(function () {<br />
        $(‘#newData’).hide();<br />
        loadinitialData();<br />
    });<br />
[/js]</p>
<p>The following is the function definition for the loadinitialData() function.</p>
<p>[js]<br />
function loadinitialData() {<br />
     jsonObject = $.parseJSON(data);<br />
     var html = ‘&lt;table&gt;&lt;th&gt;Year&lt;/th&gt;&lt;th&gt;X Value&lt;/th&gt;&lt;th&gt;Y Value&lt;/th&gt;’;<br />
     for (i = 0; i &lt; jsonObject.length; i++) {<br />
         html += ‘&lt;tr&gt;&lt;td&gt;’ + jsonObject[i].name + ‘&lt;/td&gt;&lt;td&gt;’ + jsonObject[i].data[0].x + ‘&lt;/td&gt;&lt;td&gt;’ + jsonObject[i].data[0].y + ‘&lt;/td&gt;&lt;/tr&gt;’;<br />
     }<br />
     html += ‘&lt;/table&gt;’;<br />
     $(‘#initialData’).append(html);<br />
 }<br />
[/js]</p>
<p>What we are doing here is parsing our data and appending the data to our UI element using a for loop.</p>
<p>Now after running it, you will get the following output.</p>
<p><img decoding="async" src="http://www.c-sharpcorner.com/UploadFile/65794e/find-objects-with-same-property-and-separate-them/Images/get%20output.jpg" alt="" /></p>
<p>We have successfully formatted our data and shown it to our UI. Cool, right?</p>
<p>So shall we go and separate our data? I guess you said “Yes”. Awesome. Now we will create a click event for our “Make me sort” button as in the following:</p>
<p>[js]<br />
$(‘#separateme’).click(function () {<br />
         loadnewData();<br />
         $(‘#separateme’).hide();<br />
         $(‘#newData’).show();<br />
     });<br />
[/js]</p>
<p>Here is the definition of the loadnewData() function.</p>
<p>[js]<br />
function loadnewData() {<br />
      for (i = 0; i &lt; uniqueNames.length; i++) {<br />
          var currentName = uniqueNames[i];<br />
          var uniqueDataArray = $.grep(jsonObject, function (data) {<br />
              return data.name == currentName;<br />
          });<br />
          var html = ‘&lt;table&gt;&lt;th&gt;Year&lt;/th&gt;&lt;th&gt;X Value&lt;/th&gt;&lt;th&gt;Y Value&lt;/th&gt;’;<br />
          for (j = 0; j &lt; uniqueDataArray.length; j++) {<br />
              html += ‘&lt;tr&gt;&lt;td&gt;’ + uniqueDataArray[j].name + ‘&lt;/td&gt;&lt;td&gt;’ + uniqueDataArray[j].data[0].x + ‘&lt;/td&gt;&lt;td&gt;’ + uniqueDataArray[j].data[0].y + ‘&lt;/td&gt;&lt;/tr&gt;’;<br />
          }<br />
          html += ‘&lt;/table&gt;’;<br />
          $(‘#newData’).append(html);<br />
      }<br />
  }<br />
[/js]</p>
<p>Now I guess you could determine the difference of both the loadinitialData() and loadnewData() functions. Yeah, you are right, we are using a function “grep” there.</p>
<p>[js]<br />
var uniqueDataArray = $.grep(jsonObject, function (data) {<br />
        return data.name == currentName;<br />
        });<br />
[/js]<br />
What our “grep” function does is, it will take all objects at a time that has the property “name” as currentName.<br />
[js]<br />
return data.name == currentName;<br />
[/js]</p>
<p>Once that is done, we will create a separate HTML table for each property and bind it to our parent element. Shall we now look into the complete code? We have done everything.</p>
<p><strong>Complete Code</strong></p>
<p>[html]<br />
&lt;!DOCTYPE html&gt;<br />
&lt;html&gt;<br />
&lt;head&gt;<br />
    &lt;title&gt;Find JSON Object by its property,separate and show demo – Sibeesh Passion&lt;/title&gt;<br />
    &lt;script src=“jquery-2.1.4.min.js”&gt;&lt;/script&gt;<br />
    &lt;style&gt;<br />
        #initialData {<br />
            border: 1px solid #999;<br />
            width:220px;<br />
            padding:10px;<br />
            float:left;<br />
        }<br />
        #newData {<br />
            border: 1px solid #999;<br />
            width:220px;<br />
            padding:10px;<br />
            float:left;<br />
        }<br />
         td {<br />
            border: 1px solid #ccc;<br />
            padding: 5px;<br />
            text-align: center;<br />
        }<br />
    &lt;/style&gt;<br />
    &lt;script&gt;<br />
        var data = ‘[{“name”:2014,”data”:[{“x”:”1″,”y”:222808746.81}]},{“name”:2013,”data”:[{“x”:”2″,”y”:289647045.18}]},{“name”:2014,”data”:[{“x”:”2″,”y”:285136890.07}]},{“name”:2013,”data”:[{“x”:”3″,”y”:370853178.74}]},{“name”:2014,”data”:[{“x”:”3″,”y”:403272964.28}]},{“name”:2012,”data”:[{“x”:”4″,”y”:217294031.36}]},{“name”:2013,”data”:[{“x”:”4″,”y”:224715039.94}]},{“name”:2014,”data”:[{“x”:”4″,”y”:249034460.23}]},{“name”:2012,”data”:[{“x”:”5″,”y”:215978054.15}]},{“name”:2013,”data”:[{“x”:”5″,”y”:241211810.92}]},{“name”:2014,”data”:[{“x”:”5″,”y”:245950715.8}]},{“name”:2012,”data”:[{“x”:”6″,”y”:262898180.85}]},{“name”:2013,”data”:[{“x”:”6″,”y”:280550623.51}]},{“name”:2014,”data”:[{“x”:”6″,”y”:295780079.03}]},{“name”:2012,”data”:[{“x”:”7″,”y”:217310275.85}]},{“name”:2013,”data”:[{“x”:”7″,”y”:230973675.47}]},{“name”:2014,”data”:[{“x”:”7″,”y”:238227382.03}]}]’;<br />
        var jsonObject;<br />
        var uniqueNames = [2013, 2012, 2014];<br />
        $(function () {<br />
            $(‘#newData’).hide();<br />
            loadinitialData();<br />
            $(‘#separateme’).click(function () {<br />
                loadnewData();<br />
                $(‘#separateme’).hide();<br />
                $(‘#newData’).show();<br />
            });<br />
        });<br />
        function loadinitialData() {<br />
            jsonObject = $.parseJSON(data);<br />
            var html = ‘&lt;table&gt;&lt;th&gt;Year&lt;/th&gt;&lt;th&gt;X Value&lt;/th&gt;&lt;th&gt;Y Value&lt;/th&gt;’;<br />
            for (i = 0; i &lt; jsonObject.length; i++) {<br />
                html += ‘&lt;tr&gt;&lt;td&gt;’ + jsonObject[i].name + ‘&lt;/td&gt;&lt;td&gt;’ + jsonObject[i].data[0].x + ‘&lt;/td&gt;&lt;td&gt;’ + jsonObject[i].data[0].y + ‘&lt;/td&gt;&lt;/tr&gt;’;<br />
            }<br />
            html += ‘&lt;/table&gt;’;<br />
            $(‘#initialData’).append(html);<br />
        }<br />
        function loadnewData() {<br />
            for (i = 0; i &lt; uniqueNames.length; i++) {<br />
                var currentName = uniqueNames[i];<br />
                var uniqueDataArray = $.grep(jsonObject, function (data) {<br />
                    return data.name == currentName;<br />
                });<br />
                var html = ‘&lt;table&gt;&lt;th&gt;Year&lt;/th&gt;&lt;th&gt;X Value&lt;/th&gt;&lt;th&gt;Y Value&lt;/th&gt;’;<br />
                for (j = 0; j &lt; uniqueDataArray.length; j++) {<br />
                    html += ‘&lt;tr&gt;&lt;td&gt;’ + uniqueDataArray[j].name + ‘&lt;/td&gt;&lt;td&gt;’ + uniqueDataArray[j].data[0].x + ‘&lt;/td&gt;&lt;td&gt;’ + uniqueDataArray[j].data[0].y + ‘&lt;/td&gt;&lt;/tr&gt;’;<br />
                }<br />
                html += ‘&lt;/table&gt;’;<br />
                $(‘#newData’).append(html);<br />
            }<br />
        }<br />
    &lt;/script&gt;<br />
&lt;/head&gt;<br />
&lt;body&gt;<br />
    &lt;div id=“initialData”&gt;&lt;/div&gt;<br />
    &lt;div id=“newData”&gt;&lt;/div&gt;<br />
    &lt;button id=“separateme”&gt;Make Me Separate&lt;/button&gt;<br />
&lt;/body&gt;<br />
&lt;/html&gt;<br />
[/html]<br />
Now it is time to see our output as in the following.</p>
<p><strong>output</strong></p>
<p><img decoding="async" src="http://www.c-sharpcorner.com/UploadFile/65794e/find-objects-with-same-property-and-separate-them/Images/output.jpg" alt="" /></p>
<p>You can find we have separated our object and shown it in a separate table. Cool. That is all for the day. I will return with another article soon.</p>
<p><strong>Conclusion</strong></p>
<p>I hope you liked this article. Please share with me your valuable thoughts and comments. Your feedback is always welcomed.<br />
Thanks in advance. Happy coding!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/find-json-objects-with-same-property-and-separate-them/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Convert Microsoft ADOMD Cell Set to JSON</title>
		<link>https://mail.sibeeshpassion.com/convert-microsoft-adomd-cell-set-to-json/</link>
					<comments>https://mail.sibeeshpassion.com/convert-microsoft-adomd-cell-set-to-json/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sun, 29 Mar 2015 20:08:15 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[Json]]></category>
		<category><![CDATA[Microsoft ADOMD]]></category>
		<category><![CDATA[ADOMD]]></category>
		<category><![CDATA[ADOMD CellSet]]></category>
		<category><![CDATA[CellSet JSON]]></category>
		<category><![CDATA[Convert CellSet to JSON]]></category>
		<category><![CDATA[Convert Microsoft ADOMD Cell Set to JSON]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=1381</guid>

					<description><![CDATA[In this article we will learn how we can convert Microsoft ADOMD cell sets to JSON. There are few possible ways to convert a CellSet to JSON, Here by I am sharing you one among that options. We will create a function which accepts cellset as the argument and we will loop through the axes of cellset and bind the values according to a string builder using a JsonWriter class. I hope you will like it. Background For the past few months I have been working with Microsoft ADOMD data sources. And I have written some article also that will [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this article we will learn how we can convert Microsoft ADOMD cell sets to JSON. There are few possible ways to convert a CellSet to JSON, Here by I am sharing you one among that options. We will create a function which accepts cellset as the argument and we will loop through the axes of cellset and bind the values according to a string builder using a JsonWriter class. I hope you will like it.</p>
<p><strong>Background</strong></p>
<p>For the past few months I have been working with Microsoft ADOMD data sources. And I have written some article also that will describe the problems I have encountered so far. If you are new to ADOMD I strongly recommend that read my previous articles that you may find useful when you work with ADOMD data sources. You can find those article links here.</p>
<li><a href="http://sibeeshpassion.com/how-to-convert-microsoft-adomd-data-source-to-json/" target="_blank" rel="noopener">How to Convert Microsoft ADOMD Data Source to JSON</a></li>
<li><a href="http://sibeeshpassion.com/convert-cellset-to-html-table-and-from-html-to-json-to-array/" target="_blank" rel="noopener">Convert CellSet to HTML Table and From HTML to JSON and to Array</a></li>
<p><strong>Why </strong></p>
<p>You might think, why am I again using the methods described in the preceding two articles. I will answer that. I have encountered some issues with those methods. When you use a data adapter or data reader as explained in the first link (How to Convert Microsoft ADOMD Data Source to JSON) you always get the values as normal values instead of formatted values. For example even if the value contains $ or %, you will always get values without those symbols. So your application won&#8217;t let the user identify which one is currency or which one is %. In my case it was high chart and high maps. When the user hovers over a specific area, I need to show the measure values in the tooltip. </p>
<p>So in that case I was forced to use the cell set again, where there is an option that we can select the formatted value. I will show you that in my function.</p>
<p><strong>Using the code</strong></p>
<p>The following is the function that does what was explained above.<br />
[csharp]<br />
private string BuildBubbleMap(CellSet cst)<br />
{<br />
    try<br />
    {<br />
        StringBuilder sb = new StringBuilder();<br />
        StringWriter sw = new StringWriter(sb);<br />
        string columnName = string.Empty;<br />
        string fieldVal = string.Empty;<br />
        //check if any axes were returned else throw error.<br />
        int axes_count = cst.Axes.Count;<br />
        if (axes_count == 0)<br />
            throw new Exception(&quot;No data returned for the selection&quot;);  </p>
<p>        //if axes count is not 2<br />
        if (axes_count != 2)<br />
            throw new Exception(&quot;The code support only queries with two axes&quot;);  </p>
<p>        //if no position on either row or column throw error<br />
        if (!(cst.Axes[0].Positions.Count &gt; 0) &amp;&amp; !(cst.Axes[1].Positions.Count &gt; 0))<br />
            throw new Exception(&quot;No data returned for the selection&quot;);  </p>
<p>        int cur_row, cur_col, col_count, row_count, col_dim_count, row_dim_count;<br />
        row_dim_count = 0;  </p>
<p>        //Number of dimensions on the column<br />
        col_dim_count = cst.Axes[0].Positions[0].Members.Count;  </p>
<p>        //Number of dimensions on the row<br />
        if (cst.Axes[1].Positions.Count &gt; 0)<br />
        {<br />
            if (cst.Axes[1].Positions[0].Members.Count &gt; 0)<br />
                row_dim_count = cst.Axes[1].Positions[0].Members.Count;<br />
        }<br />
        //Total rows and columns<br />
        row_count = cst.Axes[1].Positions.Count + col_dim_count;  //number of rows + rows for column headers<br />
        col_count = cst.Axes[0].Positions.Count + row_dim_count;  //number of columns + columns for row headers  </p>
<p>        using (JsonWriter myJson = new JsonTextWriter(sw))<br />
        {<br />
            myJson.WriteStartArray();<br />
            for (cur_row = 0; cur_row &lt; row_count-1; cur_row++)<br />
            {<br />
                myJson.WriteStartObject();<br />
                for (cur_col = 0; cur_col &lt; col_count-1; cur_col++)<br />
                {<br />
                    //Looping for dimension headers<br />
                    columnName = cst.Axes[1].Positions[cur_row].Members[cur_col].ParentLevel.ToString().Replace(&quot;{&quot;, &quot;&quot;).Replace(&quot;}&quot;, &quot;&quot;).Trim();<br />
                    fieldVal = cst.Axes[1].Positions[cur_row].Members[cur_col].Caption.Replace(&quot;,&quot;, &quot; &quot;);<br />
                    //If the value is null, I dont need that to be included<br />
                    if ((columnName == null || columnName == &quot;&quot; || columnName.ToLower() == &quot;undefined&quot; || columnName.ToLower() == &quot;null&quot; ||<br />
                        columnName.ToLower() == &quot;(null)&quot; || columnName.ToLower() == &quot;unknown&quot;)||(fieldVal == null || fieldVal == &quot;&quot; ||<br />
                        fieldVal.ToLower() == &quot;undefined&quot; || fieldVal.ToLower() == &quot;null&quot; ||<br />
                        fieldVal.ToLower() == &quot;(null)&quot; || fieldVal.ToLower() == &quot;unknown&quot;))<br />
                        break;<br />
                    //Map expect the header as lat and lon, so here we are changing that.<br />
                    if (columnName.ToLower() == &quot;latitude&quot;)<br />
                        columnName = &quot;lat&quot;;<br />
                    else if (columnName.ToLower() == &quot;longitude&quot;)<br />
                        columnName = &quot;lon&quot;;                              </p>
<p>                    myJson.WritePropertyName(columnName);<br />
                    myJson.WriteValue(fieldVal);<br />
                }<br />
                //Looping for measure headers<br />
                myJson.WritePropertyName(cst.Axes[0].Positions[0].Members[0].Caption.Replace(&quot;,&quot;, &quot; &quot;).Trim());<br />
                myJson.WriteValue(cst[cur_row].FormattedValue);<br />
               //Please be noted that we are using FormattedValue here.<br />
                myJson.WriteEndObject();<br />
            }<br />
            myJson.WriteEndArray();<br />
        }<br />
        cst = null;<br />
        return sw.ToString();<br />
    }<br />
    catch (Exception)<br />
    {<br />
        cst = null;<br />
        throw;<br />
    }<br />
}<br />
[/csharp]</p>
<p>You can see that this function expects the parameter cell set. Here we are finding the axis (Axis0 and Axis 1). According to my ADOMD query my dimensions are in Axis 1, so that I need to determine the caption for each dimension from the cell set. Once I determine the dimensions I am writing that to the <em>StringBuilder </em>using the method <em>WritePropertyName() </em> of the <a href="http://sibeeshpassion.com/tag/json/" target="_blank" rel="noopener">JSON </a> Writer class. To use this class you must include the Newtonsoft DLL as in the following.<br />
[csharp]<br />
using Newtonsoft.Json;<br />
[/csharp]</p>
<p>Once that is over, I am writing the value for those dimensions using the WriteValue() method of the JSON writer class.</p>
<p>I am doing that for the measures also. You can see these implementations in my code. Finally I am creating the proper JSON here and returning that.</p>
<p>To use this function you need to build the cell set first. You can do that as follows.<br />
[csharp]<br />
using (AdomdConnection conn = new AdomdConnection(myConnection))<br />
{<br />
    conn.Open();<br />
    using (AdomdCommand cmd = new AdomdCommand(query, conn))<br />
    {<br />
    cmd.CommandTimeout = connectionTimeout;<br />
    cst = cmd.ExecuteCellSet();<br />
    }<br />
 }<br />
[/csharp]</p>
<p>Once you get the cell set, just pass the cell set to the preceding function, it will return the JSON you need. You can easily bind it to any client-side tool (for example, High Chart and High Maps).</p>
<p><strong>Conclusion</strong></p>
<p>Have you ever gone through this kind of requirement. Did I miss anything that you may think which is needed?. I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C-Sharp Corner, Stack Overflow, Asp.Net Forums or Code Project instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I am able to.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/convert-microsoft-adomd-cell-set-to-json/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to Convert Microsoft ADOMD Data Source to JSON</title>
		<link>https://mail.sibeeshpassion.com/how-to-convert-microsoft-adomd-data-source-to-json/</link>
					<comments>https://mail.sibeeshpassion.com/how-to-convert-microsoft-adomd-data-source-to-json/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Thu, 29 Jan 2015 20:04:54 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Json]]></category>
		<category><![CDATA[Microsoft ADOMD]]></category>
		<category><![CDATA[ADOMD]]></category>
		<category><![CDATA[ADOMD CellSet]]></category>
		<category><![CDATA[CellSet JSON]]></category>
		<category><![CDATA[Convert CellSet to JSON]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=1331</guid>

					<description><![CDATA[Introduction Hi all, I hope you are all fine. This article helps you to understand how to convert your ADOMD data source into the JavaScript Object Notation (JSON) format. If you are new to ADOMD, please read here. As I said, we will convert the source to JSON, so you must understand what JSON is and its importance. Am I right? Important of JSON JSON stands for JavaScript Object Notation (basically JSON itself is JavaScript). It is a data format that we can format and analyze using JavaScript. It is easy to use. You can get more here. Background For [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>Hi all, I hope you are all fine. This article helps you to understand how to convert your ADOMD data source into the JavaScript Object Notation (JSON) format. If you are new to ADOMD, please read <a href="https://technet.microsoft.com/en-us/library/ms123477(v=sql.110).aspx" rel="nofollow">here</a>.</p>
<p>As I said, we will convert the source to JSON, so you must understand what JSON is and its importance. Am I right?</p>
<p><strong>Important of JSON</strong></p>
<p>JSON stands for JavaScript Object Notation (basically JSON itself is JavaScript). It is a data format that we can format and analyze using JavaScript. It is easy to use. You can get more <a href="http://xfront.com/json/index.html" rel="nofollow">here</a>.</p>
<p><strong>Background</strong></p>
<p>For the past few months I am working on ADOMD data sources. When you have become experienced in SQL, you may encounter some difficulties to play with sources. As far as my experience is concerned, playing with the data is not as easy as in SQL in ADOMD. The ADOMD data source may be an Excel file. In my case what exactly the client is doing was uploading the Excel files that they have created, to the DB.</p>
<p>Getting back to the point, when you have a client-side grid that accepts data in only JSON format in your ADOMD application, what will you do? I have searched for a solution to convert the source to the JSON for many days. But I could not find a solution. So I came up with the idea of converting the ADOMD data source (Cell Set) to a HTML table and in the client-side convert that to JSON. You can read that article <a href="http://sibeeshpassion.com/Convert-CellSet-to-HTML-table-And-From-HTML-To-Json-To-Array.html" rel="nofollow">here</a>.</p>
<p>Now that was in the initial stage, where I was new to ADOMD. We developers never stop Googling, right? To be frank I am passionate about R&amp;D work (in which we may need to search more and more). Now I have discovered some more methods to convert the source to JSON. I thought to share that information, so that someone may determine it is useful.</p>
<p>I am working in MVC, and I am using the below namespace for the process.</p>
<p><csharp>using Newtonsoft.Json;</csharp></p>
<p><strong>The Process</strong></p>
<p>In this I am not taking the ADOMD data source as a Cell Set that is popularly used in such applications. Here I will explain two methods or ways to do the process.</p>
<li>Using the ADOMD data adapter</li>
<li>Using the ADOMD data reader</li>
<p>In the first part we will use an adapter and fill the data into the data table and convert that to the JSON in the server-side itself. The problem in this method is, it needs many loops for formatting and creating.</p>
<p>In the second part we will use a data reader, while the object reads we will do the formatting and creating the JSON that needs only one loop. Sounds cool, right?</p>
<p><strong>Using the code</strong></p>
<p>Let us explain the first method.</p>
<li><strong>Using the ADOMD data adapter</strong></li>
<p>When you use an adapter and fill in the data table, the problem here you encounter is, the data table column name would be different and it will contain the hierarchy of the cube cells.</p>
<p><strong>For example:</strong> The data table header contains “.<strong>[MEMBER_CAPTION]</strong>”</p>
<p>So here I am just determining the actual header name from all the header columns. I am using a loop for that.</p>
<p>Please note that it is completely based on my requirements. You may want to do a different process of formatting.</p>
<p>To format I am using the following function.</p>
<p>[csharp]<br />
public DataTable HiMapColumnExcuteQuery(string query, string adoMDConnection)<br />
{<br />
    string readerString = string.Empty;<br />
    try<br />
    {<br />
        using (AdomdConnection conn = new AdomdConnection(adoMDConnection))<br />
        {<br />
            conn.Open();<br />
            using (AdomdCommand cmd = new AdomdCommand(query, conn))<br />
            {<br />
                    DataTable dt = new DataTable();<br />
                    AdomdDataAdapter da = new AdomdDataAdapter(cmd);<br />
                    da.Fill(dt);<br />
                    List&lt;string&gt; curColumn = new List&lt;string&gt;();<br />
                    string col = string.Empty;<br />
                    if (dt.Rows.Count &gt; 0 &amp;&amp; dt.Columns.Count &gt; 0)<br />
                    {<br />
                        for (int i = 0; i &lt; dt.Columns.Count; i++)<br />
                        {<br />
                            string columnName = dt.Columns[i].ColumnName.Replace(“.[MEMBER_CAPTION]”, “”).Trim();<br />
                            curColumn = columnName.Split(new string[] { “.” }, StringSplitOptions.None).ToList();<br />
                            col = curColumn[curColumn.Count – 1].Replace(“[“, “”).Replace(“]”, “”);<br />
                            if (Convert.ToString(col.Trim()).ToLower() == “latitude”)<br />
                                col = “lat”;<br />
                             if (Convert.ToString(col.Trim()).ToLower() == “longitude”)<br />
                                col = “lon”;<br />
                            dt.Columns[i].ColumnName = col;<br />
                        }<br />
                        dt.AcceptChanges();<br />
                    }<br />
                    return dt;<br />
            }<br />
        }<br />
    }<br />
    catch (Exception)<br />
    {<br />
        throw;<br />
    }<br />
    finally<br />
    {<br />
    }<br />
}<br />
[/csharp]</p>
<p>The function expects two parameters, one is the query that you need to execute and other is the connection. Here I am using this source for the Hi maps, as you all know it is important to provide the lat and lon for loading the map. So I am doing such formatting here.</p>
<p>Once the formatting is done, I can convert the data to the JSON foramt. For that I am using another function. You can see the function below.</p>
<p>[csharp]<br />
public string GetJsonWithZeroForNull(DataTable dt)<br />
{<br />
    try<br />
    {<br />
        if (dt == null)<br />
        {<br />
            throw new ArgumentNullException(“dt”);<br />
        }<br />
        System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();<br />
        serializer.MaxJsonLength = int.MaxValue;<br />
        List&lt;Dictionary&lt;string, object&gt;&gt; rows =<br />
          new List&lt;Dictionary&lt;string, object&gt;&gt;();<br />
        Dictionary&lt;string, object&gt; row = null;<br />
        foreach (DataRow dr in dt.Rows)<br />
        {<br />
            row = new Dictionary&lt;string, object&gt;();<br />
            foreach (DataColumn col in dt.Columns)<br />
            {<br />
                if (dr[col] == null || Convert.ToString(dr[col]).ToLower() == “undefined” || Convert.ToString(dr[col]).ToLower() == “unknown”)<br />
                    continue;<br />
                else<br />
                row.Add(col.ColumnName.Trim(), dr[col]);<br />
            }<br />
            rows.Add(row);<br />
        }<br />
        return serializer.Serialize(rows);<br />
    }<br />
    catch (Exception)<br />
    {<br />
        throw;<br />
    }<br />
}<br />
[/csharp]</p>
<p>Here I am omitting the data that all are not valid. At the end it will just serialize our rows and return the data in the format of JSON.</p>
<p>You can determine that if the data is greater then looping through the data twice may impact the performance.</p>
<p>And also we all know that a data reader is much better than a data adapter. If you do not understand why, please read <a href="http://stackoverflow.com/questions/1676753/sqldataadapter-vs-sqldatareader" rel="nofollow">here</a>.</p>
<li><strong>Using the ADOMD data reader</strong></li>
<p>Now we will move to the next part. Please see the following function for doing that.</p>
<p>[csharp]<br />
public string createJsonFromDataReader(string query, string adoMDConnection)<br />
   {<br />
      string readerString = string.Empty;<br />
      try<br />
      {<br />
          List&lt;string&gt; curColumn = new List&lt;string&gt;();<br />
          StringBuilder sb = new StringBuilder();<br />
          StringWriter sw = new StringWriter(sb);<br />
          string columnName = string.Empty;<br />
          string fieldVal = string.Empty;<br />
          string prevFieldVal = string.Empty;<br />
          AdomdDataReader rdr;<br />
          using (AdomdConnection conn = new AdomdConnection(adoMDConnection))<br />
          {<br />
              conn.Open();<br />
              using (AdomdCommand cmd = new AdomdCommand(query, conn))<br />
              {<br />
                  //cmd.Properties.Add(“ReturnCellProperties”, true);<br />
                  rdr = cmd.ExecuteReader();<br />
                  if (rdr != null)<br />
                  {<br />
                      using (JsonWriter myJson = new JsonTextWriter(sw))<br />
                      {<br />
                          myJson.WriteStartArray();<br />
                          while (rdr.Read())<br />
                          {<br />
                              myJson.WriteStartObject();<br />
                              int fields = rdr.FieldCount;<br />
                              for (int i = 0; i &lt; fields; i++)<br />
                              {<br />
                                  if (rdr[i] != null )<br />
                                  {<br />
                                      fieldVal = rdr[i].ToString();<br />
                                      if (i != 0 &amp;&amp; rdr[i-1] != null)<br />
                                          prevFieldVal = rdr[i – 1].ToString();<br />
                                      else<br />
                                          prevFieldVal = “First”;<br />
                                      if ((fieldVal == null || fieldVal.ToLower().Trim() == “undefined” || fieldVal.ToLower().Trim() == “unknown”)<br />
                                          &amp;&amp; (prevFieldVal == null || prevFieldVal.ToLower().Trim() == “undefined” || prevFieldVal.ToLower().Trim() == “unknown”))<br />
                                      {<br />
                                          continue;<br />
                                      }<br />
                                      else<br />
                                      {<br />
                                          columnName = rdr.GetName(i).Replace(“.[MEMBER_CAPTION]”, “”).Trim();<br />
                                          curColumn = columnName.Split(new string[] { “.” }, StringSplitOptions.None).ToList();<br />
                                          columnName = curColumn[curColumn.Count – 1].Replace(“[“, “”).Replace(“]”, “”);<br />
                                          if (Convert.ToString(columnName.Trim()).ToLower() == “latitude”)<br />
                                              columnName = “lat”;<br />
                                          if (Convert.ToString(columnName.Trim()).ToLower() == “longitude”)<br />
                                              columnName = “lon”;<br />
                                          myJson.WritePropertyName(columnName);<br />
                                          myJson.WriteValue(rdr[i]);<br />
                                      }<br />
                                  }<br />
                              }<br />
                              myJson.WriteEndObject();<br />
                          }<br />
                          myJson.WriteEndArray();<br />
                      }<br />
                  }<br />
                  else<br />
                  {<br />
                      return “No Records to display”;<br />
                  }<br />
              }<br />
          }<br />
          return sw.ToString();<br />
      }<br />
      catch (Exception)<br />
      {<br />
          throw;<br />
      }<br />
      finally<br />
      {<br />
      }<br />
}<br />
[/csharp]</p>
<p>Please understand that I have created an object (myJson) for the class JsonWriter. Our complete process is based on this object. Again the complete logic and formatting conditions are based on my requirements.</p>
<p>Here we are using built-in functions of the JsonWriter class. Let us list them.</p>
<li>WriteStartArray()</li>
<li>WritePropertyName()</li>
<li>WriteValue()</li>
<li>WriteEndObject()</li>
<li>WriteEndArray()</li>
<p>You can see that I am doing both the formatting and creating of the JSON with one loop that will improve the performance.<br />
In the process we are appending the values to the string builder and finally the function will return the JSON in the required format.</p>
<p>You have done it. Great.</p>
<p>Please use StringBuilder in your applications instead of string. Use a string variable only if it is necessary. Using string variables will create separate memory allocations whenever you assign values to it. Please read more here.</p>
<li><a href="http://stackoverflow.com/questions/18453458/string-builder-vs-string-concatenation" rel="nofollow">String builder vs string concatenation</a></li>
<li><a href="http://stackoverflow.com/questions/3069416/difference-between-string-and-stringbuilder-in-c-sharp" rel="nofollow">Difference between string and StringBuilder in C#</a></li>
<p><strong>Note: </strong>I have implemented this for loading high maps. That&#8217;s why I have formatted it in this way. Please use your own formatting depending on your requirements.</p>
<p><strong>Point of interest</strong></p>
<p>ADOMD, ADOMD data source to JSON, ADOMD Cell Set to JSON, ADOMD data adapter to JSON, ADOMD data reader to JSON.</p>
<p><strong>Conclusion</strong></p>
<p>Please do not forget to give your valuable suggestions.</p>
<p>That is all for the day, will see you in another article.</p>
<p>Kindest Regards<br />
<a href="http://sibeeshpassion.com" rel="nofollow">Sibeesh Venu</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/how-to-convert-microsoft-adomd-data-source-to-json/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Convert CellSet to HTML Table and From HTML to JSON and to Array</title>
		<link>https://mail.sibeeshpassion.com/convert-cellset-to-html-table-and-from-html-to-json-to-array/</link>
					<comments>https://mail.sibeeshpassion.com/convert-cellset-to-html-table-and-from-html-to-json-to-array/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Wed, 29 Oct 2014 19:19:46 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Json]]></category>
		<category><![CDATA[Microsoft ADOMD]]></category>
		<category><![CDATA[Microsoft Technologies]]></category>
		<category><![CDATA[ADOMD]]></category>
		<category><![CDATA[ADOMD Cell]]></category>
		<category><![CDATA[ADOMD CellSet]]></category>
		<category><![CDATA[CellSet]]></category>
		<category><![CDATA[CellSet JSON]]></category>
		<category><![CDATA[Convert CellSet to JSON]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=591</guid>

					<description><![CDATA[Introduction For the past few days I have been working on ADOMD and MDX. I encountered a situation where I need to convert my Cell Set to a HTML table and render it to the client-side Grid. So I thought of sharing that with you all. This article has been selected as article of the day Monday, November 10, 2014 in http://www.asp.net/community/articles (Convert CellSet to HTML Table, and from HTML to Json, Array) Background If you are new to ADOMD, you can refer to the following links: Microsoft Analysis Services 2005: Displaying a grid using ADOMD.NET and MDX Manipulate and [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>For the past few days I have been working on ADOMD and MDX. I encountered a situation where I need to convert my Cell Set to a HTML table and render it to the client-side Grid. So I thought of sharing that with you all.</p>
<p>This article has been selected as article of the day Monday, November 10, 2014 in http://www.asp.net/community/articles (Convert CellSet to HTML Table, and from HTML to Json, Array)</p>
<p><strong>Background</strong></p>
<p>If you are new to ADOMD, you can refer to the following links:</p>
<p><a href="http://www.codeproject.com/Articles/28290/Microsoft-Analysis-Services-Displaying-a-grid" target="_blank" rel="noopener">Microsoft Analysis Services 2005: Displaying a grid using ADOMD.NET and MDX</a><br />
<a href="http://www.microsoft.com/msj/0899/mdx/mdx.aspx" target="_blank" rel="noopener">Manipulate and Query OLAP Data Using ADOMD and Multidimensional Expressions</a></p>
<p><strong>Why</strong></p>
<p>As I have already said, in my current project we are using MDX cubes, so in the server-side we will get only a CellSet. So I have tried very much to convert the CellSet to the JSON for this JQX grid alone (all other Grids in the project use a HTML table as the data source). But I couldn’t find any good way for that. So I thought of getting the HTML table from the CellSet as in the other grid at the server side. And I knew how to formulate the Array and JSON from an HTML table. Here I am sharing that information.</p>
<p>Please provide your valuable suggestions for improvement.</p>
<p><strong>Using the Code</strong></p>
<p>We modify the code as per our needs from the preceding specified articles and bind to an HtmlTextWriter. We have created a function called renderHTML() that will accept CellSet as an argument. Here, I will show the code.<br />
[csharp]<br />
try<br />
            {<br />
                System.Text.StringBuilder result = new System.Text.StringBuilder();<br />
                //check if any axes were returned else throw error.<br />
                int axes_count = cst.Axes.Count;<br />
                if (axes_count == 0)<br />
                    throw new Exception(“No data returned for the selection”);<br />
                //if axes count is not 2<br />
                if (axes_count != 2)<br />
                    throw new Exception(“The sample code support only queries with two axes”);<br />
                //if no position on either row or column throw error<br />
                if (!(cst.Axes[0].Positions.Count &gt; 0) &amp;&amp; !(cst.Axes[1].Positions.Count &gt; 0))<br />
                    throw new Exception(“No data returned for the selection”);<br />
                int cur_row, cur_col, col_count, row_count, col_dim_count, row_dim_count;<br />
                cur_row = cur_col = col_count = row_count = col_dim_count = row_dim_count = 0;<br />
                //Number of dimensions on the column<br />
                col_dim_count = cst.Axes[0].Positions[0].Members.Count;<br />
                //Number of dimensions on the row<br />
                if (cst.Axes[1].Positions[0].Members.Count &gt; 0)<br />
                    row_dim_count = cst.Axes[1].Positions[0].Members.Count;<br />
                //Total rows and columns<br />
                row_count = cst.Axes[1].Positions.Count +<br />
                    col_dim_count;  //number of rows + rows for column headers<br />
                col_count = cst.Axes[0].Positions.Count +<br />
                    row_dim_count;  //number of columns + columns for row headers<br />
                //gridPanel.ClientIDMode = System.Web.UI.ClientIDMode.AutoID;<br />
                //////lets clear any controls under the grid panel<br />
                //gridPanel.Controls.Clear();<br />
                ////Add new server side table control to gridPanel<br />
                Table tblgrid = new Table();<br />
                tblgrid.Attributes.Add(“Id”, “myhtmltab”);<br />
                tblgrid.Attributes.Add(“class”, “display”);<br />
                //We will use label control to add text to the table cell<br />
                Label lbl;<br />
                string previousText = “”;<br />
                int colSpan = 1;<br />
                for (cur_row = 0; cur_row &lt; row_count; cur_row++)<br />
                {<br />
                    //add new row to table<br />
                    TableRow tr = new TableRow();<br />
                    for (cur_col = 0; cur_col &lt; col_count; cur_col++)<br />
                    {<br />
                        //create new cell and instance of label<br />
                        TableCell td = new TableCell();<br />
                        TableHeaderCell th = new TableHeaderCell();<br />
                        lbl = new Label();<br />
                        //check if we are writing to a ROW having column header<br />
                        if (cur_row &lt; col_dim_count)<br />
                        {<br />
                            //check if we are writing to a cell having row header<br />
                            if (cur_col &lt; row_dim_count)<br />
                            {<br />
                                //this should be empty cell — it’s on top left of the grid.<br />
                                //result.Append(” ,”);<br />
                                lbl.Text = ” “;<br />
                                td.CssClass = “titleAllLockedCell”; //this locks<br />
                                    //the cell so it doesn’t scroll upwards nor leftwards<br />
                            }<br />
                            else<br />
                            {<br />
                                //this is a column header cell — use member caption for header<br />
                                //result.Append(cst.Axes[0].Positions[cur_col –<br />
                                //    row_dim_count].Members[cur_row].Caption + “,”);<br />
                                //if (cur_row &lt; 1)<br />
                                //{<br />
                                    lbl.Text = cst.Axes[0].Positions[cur_col – row_dim_count].Members[cur_row].Caption;<br />
                                    th.CssClass = “titleTopLockedCell”; // this lockeders<br />
                                            //the cell so it doesn’t scroll upwards<br />
                                //}<br />
                                if (lbl.Text == previousText)<br />
                                {<br />
                                    colSpan++;<br />
                                }<br />
                                else<br />
                                {<br />
                                    colSpan = 1;<br />
                                }<br />
                            }<br />
                        }<br />
                        else<br />
                        {<br />
                            //We are here.. so we are writing a row having data (not column headers)<br />
                            //check if we are writing to a cell having row header<br />
                            if (cur_col &lt; row_dim_count)<br />
                            {<br />
                                //this is a row header cell — use member caption for header<br />
                                lbl.Text = cst.Axes[1].Positions[cur_row –<br />
                                col_dim_count].Members[cur_col].Caption.Replace(“,”, ” “);<br />
                                td.CssClass = “titleLeftLockedCell”; // this lockeders<br />
                                    //the cell so it doesn’t scroll leftwards<br />
                            }<br />
                            else<br />
                            {<br />
                                //this is data cell.. so we write the Formatted value of the cell.<br />
                                lbl.Text = cst[cur_col – row_dim_count, cur_row – col_dim_count].FormattedValue;<br />
                                //td.InnerText = cst[cur_col – row_dim_count,<br />
                                //cur_row – col_dim_count].FormattedValue;<br />
                                td.CssClass = “valueCell”; //this  right<br />
                                        //aligns the values in the column<br />
                            }<br />
                            //turn the wrapping off for row header and data cells.<br />
                            td.Wrap = true;<br />
                        }<br />
                        if (((lbl.Text != previousText) || (lbl.Text == ” “))<br />
                            &amp;&amp; (cur_row &lt; col_dim_count))<br />
                        {<br />
                            tr.TableSection = TableRowSection.TableHeader;<br />
                            th.Text = “HEADER”;<br />
                            th.Controls.Add(lbl);<br />
                            tr.Cells.Add(th);<br />
                            tblgrid.Rows.Add(tr);<br />
                        }<br />
                        else if ((lbl.Text != previousText) || (lbl.Text == ” “) ||<br />
                            (lbl.Text == null) || (lbl.Text == “”))<br />
                        {<br />
                            td.Controls.Add(lbl);<br />
                            tr.Cells.Add(td);<br />
                            tblgrid.Rows.Add(tr);<br />
                        }<br />
                        else<br />
                        {<br />
                            try<br />
                            {<br />
                                tr.Cells[tr.Cells.Count – 1].ColumnSpan = colSpan;<br />
                            }<br />
                            catch<br />
                            {<br />
                            }<br />
                        }<br />
                        if (cur_row &lt; col_dim_count)<br />
                            previousText = lbl.Text;<br />
                    }<br />
                    //result.AppendLine();<br />
                }<br />
                using (StringWriter writer = new StringWriter())<br />
                {<br />
                    HtmlTextWriter htw = new HtmlTextWriter(writer);<br />
                    tblgrid.RenderControl(htw);<br />
                    return htw.InnerWriter.ToString();<br />
                }<br />
            }<br />
            catch (Exception ex)<br />
            {<br />
                throw ex;<br />
            }<br />
[/csharp]</p>
<p>Finally, the function will return the output as an HTML table with the id “myhtmltab” where all the th, tr and td tags are rendered.</p>
<p>Now if you want, you can convert the HTML table to an Array, JSON in the client side.</p>
<p>Now what we need to do is just add the dynamic HTML to the DOM. You can do that as follows:<br />
[js]<br />
$(‘#your element id’).html(data);<br />
[/js]</p>
<p>Please read here for more information: <a href="http://api.jquery.com/html/" target="_blank" rel="noopener">Get the HTML contents of the first element in the set of matched elements.</a></p>
<p><strong>Convert HTML to Array Dynamically in jQuery</strong></p>
<p>Let’s say you have an Ajax jQuery function that will return the output as I have shown in the output image.</p>
<p>If you are new to jQuery Ajax function, please read here:</p>
<p><a href="http://www.codeproject.com/Tips/688228/Bind-Dropdownlist-in-ASP-NET-using-jQuery-AJAX" target="_blank" rel="noopener">Bind Dropdownlist in ASP.NET using jQuery AJAX</a><br />
<a href="http://www.codeproject.com/Articles/224827/Jquery-Ajax-Calling-functions" target="_blank" rel="noopener">Jquery Ajax Calling Functions</a><br />
<a href="http://www.codeproject.com/Articles/631438/Code-Builder-for-jQuery-AJAX-Calling-Web-Services" target="_blank" rel="noopener">Code Builder for jQuery AJAX (Calling Web Services)</a></p>
<p>Then in the success of the Ajax function, you can write the code like this to formulate an array.</p>
<p>Next is to get the columns and rows from the dynamic HTML table that you just formulated using CellSet:<br />
[js]<br />
var rows = $(“#myhtmltab tbody tr”); //Select Rows , looping through every tr<br />
var columns = $(“#myhtmltab thead th”); //Select columns , looping through every th<br />
[/js]<br />
Now what we need is an Array where we can populate the data. 🙂<br />
[js]<br />
var data = [];<br />
for (var i = 0; i &lt; rows.length; i++) {<br />
    var row = rows[i];<br />
    var datarow = {};<br />
    for (var j = 0; j &lt; columns.length; j++) {<br />
        // get column’s title.<br />
        var columnName = $.trim($(columns[j]).text());<br />
        // select cell.<br />
        var cell = $(row).find(‘td:eq(‘ + j + ‘)’);<br />
        datarow[columnName] = $.trim(cell.text());<br />
    }<br />
    data[data.length] = datarow;<br />
}<br />
[/js]</p>
<p>Now this is the time to formulate a JSON from the table. 🙂</p>
<p><strong>Convert Dynamic HTML to JSON Dynamically in jQuery</strong></p>
<p>As we discussed above, here also we are looping through the column and rows. The intent behind this is to formulate a dynamic JSON to assign data to my JQX Grid (You can check this out: <a href="http://sibeeshpassion.com/Working-With-JQX-Grid-With-Filtering-And-Sorting/" target="_blank" rel="noopener">Working With JQX Grid With Filtering And Sorting</a>).<br />
[js]<br />
var varDataFields = ‘[‘;<br />
var varDataColumns = ‘[‘;<br />
var typ = ‘string’;<br />
var align = ‘center’;<br />
var width = ‘200’;<br />
var myColumns = $(“#myhtmltab thead th”);<br />
for (var j = 0; j &lt; myColumns.length; j++) {<br />
    var column = myColumns[j];<br />
    var col = $(column).text().trim();<br />
    //col = col.replace(‘&lt;span&gt;’, ”);<br />
    //col = col.replace(‘&lt;/span&gt;’, ”);<br />
    //var col = $(columns).find(‘th:get(‘ + j + ‘).find(‘ &lt; span &gt; ‘).text()’);<br />
    //if (!col == ”) {<br />
    varDataFields = varDataFields +<br />
    ‘ { \”name\” : \”‘ + col + ‘\” , \”type\” : \”‘ + typ + ‘\”},’;<br />
    varDataColumns = varDataColumns +<br />
    ‘ { \”text\” : \”‘ + col + ‘\” , \”dataField\” :  \”‘ +<br />
    col + ‘\” , \”align\” :  \”‘ + align + ‘\” , \”width\” : \”‘ + width + ‘\”},’;<br />
    //}<br />
    if (j == myColumns.length – 1) {<br />
        varDataFields = varDataFields.slice(0, -1);<br />
        varDataColumns = varDataColumns.slice(0, -1)<br />
    }<br />
}<br />
varDataFields = varDataFields + ‘]’;<br />
varDataColumns = varDataColumns + ‘]’;<br />
varDataFields = varDataFields.trim();<br />
varDataColumns = varDataColumns.trim();<br />
var DataFields = $.parseJSON(varDataFields);<br />
var DataColumns = $.parseJSON(varDataColumns);<br />
[/js]</p>
<p>So in DataFields, DataColumns, I will get the JSON in the way that I want. This I can directly bind to the JQX Grid. 🙂</p>
<p><strong>Points of Interest</strong></p>
<p>ADOMD, MDX</p>
<p><strong>History</strong></p>
<p>First version: 27-Oct-2014</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/convert-cellset-to-html-table-and-from-html-to-json-to-array/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
	</channel>
</rss>
