0

I am stuck with handling json values for a while now. I am returning json values in ajax call. Now i want to display the json in a specific format. For example, let the returned values be

{"Heading 1":["Content 1","Content 2"],"Heading 2":["Content 1","COntent 2","Content 3"],"Heading3":["Content 1"]}

I want to display in such a way that

<h4>Heading 1</h4> <input type="checkbox">Content 1<br><input type="checkbox">Content 2<br>
<h4>Heading 2</h4> <input type="checkbox">Content 1<br><input type="checkbox">Content 2<br><input type="checkbox">Content 3<br>
<h4>Heading 3</h4> <input type="checkbox">Content 1<br>

How Should I go about with this?

curious_coder
  • 2,392
  • 4
  • 25
  • 44
  • Loop through the object, put the key in an `

    `, then the value(s) in ``s.

    – gen_Eric Apr 17 '13 at 17:10
  • 1
    May be duplicate of this http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript – roshan lal Apr 17 '13 at 17:10
  • You may want to look into [one of the many available template solutions](http://garann.github.io/template-chooser/) for this sort of problem. – Pointy Apr 17 '13 at 17:12

2 Answers2

1

Try this approach:

var data, container, key, curHeading, heading, i, checkbox;

data = {"Heading 1":["Content 1","Content 2"],"Heading 2":["Content 1","COntent 2","Content 3"],"Heading3":["Content 1"]};

container = document.createElement("div");
for (key in data) {
    curHeading = data[key];
    heading = document.createElement("h4");
    heading.innerHTML = key;
    container.appendChild(heading);
    for (i = 0; i < curHeading.length; i++) {
        checkbox = document.createElement("input");
        checkbox.type = "checkbox";
        container.appendChild(checkbox);
        container.appendChild(document.createTextNode(curHeading[i]));
        container.appendChild(document.createElement("br"));
    }
}

document.body.appendChild(container);

DEMO: http://jsfiddle.net/UwSU6/1/

Where this is happening in the window.onload event (like in the jsFiddle)

Ian
  • 50,146
  • 13
  • 101
  • 111
-1
var json ={"Heading 1":["Content 1","Content 2"],"Heading 2":["Content 1","COntent 2","Content 3"],"Heading3":["Content 1"]}
obj = JSON.parse(json);


for ( evaluationHere){
    createTheElementsHEre()

}
insertHtml();
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
elopez
  • 109
  • 9