Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to show json object key and value using handlebar template?

I have started to learn handlebar.js . I am struggling to display json data .

My json look like this:

 var data={
          "record1":
          [
             {
               "first":
                      [
                       {
                         "name":"john",
                         "city":"newyork"  
                       },
                       {
                         "name":"britto",
                         "city":"bangalore"  
                       }
                      ]
             },
            {"second":
                 [
                  {
                    "name":"franklin",
                    "city":"newyork"  
                  },
                  {
                    "name":"leo",
                    "city":"bangalore"  
                  }
                ]
            }
        ]
    };

here this json is coming from server response so I don't know any key and value. I have to show key and value dynamically by using handlebar ...I have tried with eachKey but I have not got solution for that . Can anyone help me?

like image 868
silvesterprabu Avatar asked Jan 30 '14 09:01

silvesterprabu


2 Answers

You can render the keys/values of a list in a Handlebars template like this:

{{#each object}}
  {{@key}}: {{this}}
{{/each}}
like image 134
tobi Avatar answered Sep 18 '22 08:09

tobi


First thank you tobi this did lead to what I needed getting the key.

In case it was not clear for the OP "this" is referring to the current object of that iteration.

So in your case data the object has the array record1 with 2 objects that are arrays of objects: first and second.

Using each:

{{#each record1}}
    {{@key}}: {{this}}
{{/each}}

would give you: first: (object, array) second: (object, array)

You will be looping over the object (data). In this if you wanted to dig down you would need a counter to get anywhere further. I would recommend using a handlebars block helper to get there.

Here is the documentation: http://handlebarsjs.com/block_helpers.html

like image 44
nerdlyist Avatar answered Sep 18 '22 08:09

nerdlyist