Display JSON data using handlebars.js

25,584

Solution 1

One problem is the each helper, here: {{#each context.characters}}. What each does is look within the current context for the variable. You've already passed Handlebars the context object when you called res.render('/', context). So now Handlebars is looking within the context object for an attribute called context, and it won't find it. So you should change that line of code to {{#each characters}}.

The same thing applies to where you wrote {{this.name}}. I think that will actually work if you fix the other problem, but the this is unnecessary, because Handlebars looks at this (the current context) automatically. So just {{name}} should be fine there.

Finally, if you're really trying to just display the JSON file as a page of plain text, you don't need to run it through a Handlebars template. You can just use res.json(context). This will return a JSON response. If your server is configured to handle the application/json MIME type, it should render as plain text in the browser.

Solution 2

If you want to display the stringified JSON, you can use an helper

JS

Handlebars.registerHelper('toJSON', function(obj) {
    return JSON.stringify(obj, null, 3);
});

HTML <pre>{{toJSON result}}</pre>

Solution 3

Since you are iterating over objects in handlebars, it should be done as -

  {{#each context.characters}}
      {{#each this}}
         {{@key}} - {{this}}
      {{/each}}
  {{/each}}

Solution 4

If you are using it with Node.js and mongoDB this answer is for you;

Let's say you have the following response from your database called data:

{                                
  _id: "5AAAAAAAAAe04fc1a1", //some id idk
  BUSINESS: 'FLEX TAPE',          
  SHOWMAN: 'PHIL SWIFT',            
  CONTACT: 'PHIL SWIFT',         
  PHONE: '11111111113',       
  ETC: 'yes',                          
}    

What you might want to look for to display the fields is to take advantage from client-side rendering. piping the data with the classic JSON.stringify(data) as okData for instance.. then you can just reference it using the {{}} notation.

e:g.

<p id="some-id" style="display: none"> {{okData}} </p>

<script>
let jsonStrLookup = document.getElementById('some-id').innerHTML
let js = JSON.parse(jsonStrLookup)

console.log(js)
</script>

This would work for SIMPLE applications hope it helps out, and if something seems off comment, I always check on here, and will try to help you.

Share:
25,584
shelum
Author by

shelum

Updated on July 09, 2022

Comments

  • shelum
    shelum almost 2 years

    I need to figure out how to print the full JSON response onto my page (or even parts of it), but I can't seem to figure it out. I am going to eventually fill out the page with more context later.

    JS file:

    app.get('/', function(req, res) {
    var context
    
    apiLib.fetch('acct:chars', function(err, result){
        if(err) throw err
    
        context = result;
        console.log(result); 
        res.render('/', context);
    
        });
    
    });
    

    Handlebars:

     {{#each context.characters}}
     {{this.name}} 
     {{/each}}
    

    JSON Data:

    {
      "result": {
        '1234':{               //this is the character ID
          "characters": {
            "name": 'Daniel',
            "CharacterID": '1234'
            etc...
        }
       }
     }
    

    My page prints nothing, but console logs everything. I am using express.js to handle the routing.

  • shelum
    shelum over 8 years
    I just tried that and now the page doesn't even load black and I get a "failed to lookup view '[object Object]' in the views directory" error when lloading the page
  • Chandan
    Chandan over 8 years
    what does context contains .. ?
  • shelum
    shelum over 8 years
    context contains the JSON data. It is viewable in the console.
  • Chandan
    Chandan over 8 years
    can you paste it ..? or is it the same as in the question .. ?
  • shelum
    shelum over 8 years
    my server must've had a hiccup. page is loading now but there still isn't anything printed to the page. This is what shows up in the console: i.imgur.com/VhLTDri.jpg
  • Chandan
    Chandan over 8 years
    the json in the image you provided is the context value ??
  • shelum
    shelum over 8 years
    thank you. this worked! I will be building out the page with more content, I just wanted to get that out of the way first.
  • dwhieb
    dwhieb over 8 years
    @shelum happy to help! also, you might want to edit your question to clarify that you weren't trying to render it as plain text, to help future readers.don't worry about adding thank you answers or comments either: an upvote or selected answer is thanks enough! Check out some of the docs: stackoverflow.com/help/privileges/comment