Brief code but full-featured
The following is a hybrid jQuery solution that formats each data "record" into an HTML element and uses the data's properties as HTML attribute values.
The jquery each
runs the inner loop; I needed the regular JavaScript for
on the outer loop to be able to grab the property name (instead of value) for display as the heading. According to taste it can be modified for slightly different behaviour.
This is only 5 main lines of code but wrapped onto multiple lines for display:
$.get("data.php", function(data){
for (var propTitle in data) {
$('<div></div>')
.addClass('heading')
.insertBefore('#contentHere')
.text(propTitle);
$(data[propTitle]).each(function(iRec, oRec) {
$('<div></div>')
.addClass(oRec.textType)
.attr('id', 'T'+oRec.textId)
.insertBefore('#contentHere')
.text(oRec.text);
});
}
});
Produces the output
(Note: I modified the JSON data text values by prepending a number to ensure I was displaying the proper records in the proper sequence - while "debugging")
<div class="heading">
justIn
</div>
<div id="T123" class="Greeting">
1Hello
</div>
<div id="T514" class="Question">
1What's up?
</div>
<div id="T122" class="Order">
1Come over here
</div>
<div class="heading">
recent
</div>
<div id="T1255" class="Greeting">
2Hello
</div>
<div id="T6564" class="Question">
2What's up?
</div>
<div id="T0192" class="Order">
2Come over here
</div>
<div class="heading">
old
</div>
<div id="T5213" class="Greeting">
3Hello
</div>
<div id="T9758" class="Question">
3What's up?
</div>
<div id="T7655" class="Order">
3Come over here
</div>
<div id="contentHere"></div>
Apply a style sheet
<style>
.heading { font-size: 24px; text-decoration:underline }
.Greeting { color: green; }
.Question { color: blue; }
.Order { color: red; }
</style>
to get a "beautiful" looking set of data
More Info
The JSON data was used in the following way:
for each category (key name the array is held under):
- the key name is used as the section heading (e.g. justIn)
for each object held inside an array:
- 'text' becomes the content of a div
- 'textType' becomes the class of the div (hooked into a style sheet)
- 'textId' becomes the id of the div
- e.g. <div id="T122" class="Order">Come over here</div>