programador_mierder
programador_mierder

Reputation: 33

Parse json using Mustache

I've got this JSON:

{ 
status: "ok", 
posts: [ { 
          id: 1362, 
          type: "ser", 
          slug: "av-ss-xiii-3",

           fields: { 
                     price: [ "550" ], 
                     sale: [ "rent" ] 
            } 
       } ]
}

And I'm parsing it this way with mustache, but as you can see...fields is not an array of objects, it is an object with two attributes with array values...

{{#posts}}
<h1>{{type}}</h1>
        {{#fields}}
            <p> {{price}}:{{value}}</p>
         {{/fields}} 
{{/posts}}

I think I'll made a mistake during the parsing, cause it's no working for the price values.

Upvotes: 0

Views: 2809

Answers (2)

programador_mierder
programador_mierder

Reputation: 33

Finally I found it...it was a question of 'method', using .toHtml it gives nothing with arrays...using .render it works fine! Thanks

Upvotes: 0

Will Klein
Will Klein

Reputation: 2294

Your template is close to working. The problem I can see is {{value}} expects a key in the fields object that is not present. Your template currently outputs the price with a colon and then nothing:

<h1>ser</h1>
<p> 550 :</p>

Perhaps you thought {{value}} would output 550, or you meant that to output the value of sale. In both cases it is a little odd to have the values wrapped in arrays: [ "550" ]. This doesn't matter though since there is only one element in each and this does not complicate your template at all. I can only guess at what your desired output is, but allow me to demonstrate your template in a working example.

{{#posts}}
    <h1>{{type}}</h1>
    {{#fields}}
    <p> {{price}} : {{sale}}</p>
    {{/fields}}
{{/posts}}

This will output the following HTML for your data:

<h1>ser</h1>
<p> 550 : rent</p>

Here is a jsFiddle to illustrate: template with multiple posts

I took the liberty of making up a second post object to demonstrate how your data might render with a collection. I also took a guess that you might mean to output both the price and the sale values.

I think you already understand this, but to be clear, {{#fields}} ... {{/fields}} works like a conditional since fields is an object and not an array. That's fine. In the case that fields is falsy (for example, undefined or false), your template won't render the p element.

Please note I used jQuery in the jsFiddle but only for convenience to access the template and DOM elements.

I hope that helps, but let me know if you have any questions. If that's not what you're looking for, please edit your question to describe your desired output.

Upvotes: 2

Related Questions