Error when JSON fields is missing

1 view
Skip to first unread message

Vincent Pérès

unread,
May 12, 2009, 10:46:49 AM5/12/09
to chainjs
Hello,

I'm parsing and displaying results from JSON datas thanks to Chain.
But it appears an error when an element is missing ("field" is not
defined, error from Chain).

Example (missing description field in the second element) :
<docs>
<doc>
<field name="title">blabla</field>
<field name="description">blabla</field>
</doc>
<doc>
<field name="title">blabla</field>
</doc>
<doc>
<field name="title">blabla</field>
<field name="description">blabla</field>
</doc>
</docs>

Now I have two different needs :
1. builder[".description"] = "description"
I solved it by building a custom builder :
builder['.description'] = function(data, el) {
if (data['description'] != '' && data[value['field']] !=
undefined) {
return data['description'];
} else {
return '';
}
};

2. builder[".description"] = "<img src='link' alt='{description}' />"
It's working, but I case where the field is missing, I don't have an
alternative (like I wrote above).
Do you have any idea which could help me to build a custom builder and
parse a string inside, or anything else?

Thank you very much.
Vincent

Rizqi

unread,
May 12, 2009, 3:26:08 PM5/12/09
to chainjs
hi,

you can do this:

chain({
'.description': '{$data.description && $data[value
["field"]] ? description : ""}'
})

Pérès Vincent

unread,
May 13, 2009, 3:59:23 AM5/13/09
to cha...@googlegroups.com
Hello,

Huge ! Thanks very much, it helps me a lot.
And thanks for your work on Chain, I hope to launch soon an opensource project using mainly Chain as a template engine !

Cheers,
Vincent
Reply all
Reply to author
Forward
0 new messages