0

I have the following jSON data.

{
  "cluster-1": [
    "item1",
    "item2"
  ],
  "cluster-2": [
    "item3",
    "item4"
  ],
  "cluster-3": [
    "item1",
    "item2"
  ]
}

the cluster-# can be any number. (it can range from 1-50) "item#" are just strings.

I would like to separate out the data in the below format, once that is done, I would like to display in few div boxes (I don't want this, but will be helpful if you provide inputs)

I would like to print this in a TextArea box like

cluster-1
  item1
  item2

cluster-2
  item3
  item4

cluster-3
  item5
  item6

I am generating this data from a java source file, I have control over this, if the format needs to be changed.

sravanreddy001
  • 257
  • 1
  • 5
  • 17

3 Answers3

1
var data = {
          "cluster-1": [
            "item1",
            "item2"
          ],
          "cluster-2": [
            "item3",
            "item4"
          ],
          "cluster-3": [
            "item1",
            "item2"
          ]
        };

        var result = "";
        for (key in data) {
            result += key + "\n";
            for (subKey in data[key]) {
                result += "    " + data[key][subKey] + "\n";    
            }
        }

        console.log(result);
aretias
  • 341
  • 2
  • 3
  • 1
    Thanks a lot. This helped me exactly.. i had to add another line. data = jQuery.parseJSON(data); just before the for-loop – sravanreddy001 Dec 03 '12 at 04:41
1

If you are looking for ajax kind of solution then try this one:

            $.ajax({
                url: 'your json file path',
                type: 'GET',
                success: function() {
                    $.each(data[0], function(key, val) {
                        $('textareaID').val(key+'\n' + val+'\n');
                    });
                });

not tested but might be useful for you.

Jai
  • 74,255
  • 12
  • 74
  • 103
  • I am actually making ajax calls, but sending it by POST method, because of large data to be sent to server. Thanks for the inputs.. – sravanreddy001 Dec 03 '12 at 04:44
1

the answer above is about nodejs, i believe your talking about simple js+html... so instead of console.log(result) you'd do:

$("div#myOutlet").text(result);

and in your html

<div id="myOutlet">text will be placed here</div>
  • Yes, how can I create those
    tags dynamically? because, the number of cluster are not fixed in my application. So, I need tocreate # number of div tags and place each cluster data in each div tag. (Thank you, i knew this before. adding to existing tag) :)
    – sravanreddy001 Dec 03 '12 at 04:43
  • http://stackoverflow.com/questions/6840326/how-can-i-create-and-style-a-div-using-javascript – Octavio Ben-Aharon Dec 03 '12 at 13:21