Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to JSON.parse data in a Meteor template?

Tags:

meteor

Here is my scenario, the first project with Meteor: I have JSON-stringified data embedded in my MongoDB documents, as you can see in the MESSAGE key below:

{ "DATE" : "Jan 24 23:28:14",
  "MESSAGE" : **"{\"status_code\":200,\"uri\":\"172.16.156.143/content/dynamic\",\"tprocess\":3}"**,
  "_id" : ObjectId("5101c3992a1624e726000014") }

In Meteor, my client template code looks like the following basic pattern:

Template.log.logEntry = function () {
    return Messages.find({});
};

... Which works OK, but it'll obviously render the following template...

<template name="log">
    <h1>Log Entries Are:</h1>
        {{#each logEntry}}
            <div> : {{MESSAGE}} </div>
        {{/each}}
</template>

... With a non-parsed, literal string in the browser, for example,

{"status_code":200,"uri":"172.16.156.143/static/style.css","tprocess":2}

I'd love to JSON.parse() this string and do more interesting things, but I'm not sure how best to do it from the isClient context in my Meteor project's JavaScript file.

like image 547
mcauth Avatar asked Jan 15 '23 09:01

mcauth


2 Answers

Add a template helper:

Template.log.aSpecificField = function () {
  return JSON.parse(this.MESSAGE).aSpecificField;
}

which allows you to use {{aSpecificField}} within your #each loop.

like image 160
avital Avatar answered Jan 26 '23 01:01

avital


I'm not sure if this is the best way to do it (indeed, I suspect not), but this works as expected.

Template.log.helpers({
  get_uri: function () {
     return JSON.parse(this.MESSAGE).uri;
}

Calling it in the template is now just:

{{ get_uri }}
like image 25
mcauth Avatar answered Jan 25 '23 23:01

mcauth