Consider, I am sending JSON to client as follows in render page of Express (using hbs as a view engine):
res.render('MyPage.html', { layout: false, PageTitle: 'Project Name', JSON_Data: {field1:'value',field2:'value2'}});
I am able to access and set title of html page by using {{PageTitle}}, following is the code.
<title>{{PageTitle}}</title>
Now I want to show JSON_data into alert popup.
I've tried following way, but getting Uncaught SyntaxError: Unexpected token {, while debugging in chrome is shows var jsonobj = [object Object]
function fbOnBodyLoad() {
var jsonobj = {{JSON_data}};
alert(jsonobj);
}
Could any body give some idea on How to access JSON_data and show in alert
Advance Thanks
to access the inner elements of the json object, try like this
var jsonobj = "{{JSON_data.field1}}";
may be this might solve the issue.
refer
Handlebars.js parse object instead of [Object object]
You could always register a Handlebars helper to format the object into a string format (such as by using JSON.stringify), and then use that helper in your view. http://handlebarsjs.com/block_helpers.html
For me it worked by doing in the server:
res.render('pages/register', {
title: 'Register Form',
messages: req.flash('error'),
countries:JSON.stringify(countries)
});
and then I used this countries variables to assign in angular controller like this:
angular.module('languagesApp', []).controller('DemoController', function($scope) {
$scope.algo = {{-countries}};
...
Related
I'm using express server with ejs templates for client and im passing an object not a single variable from server to client side.. like
router.get('/users/info',(req,res)=>{
let data = {
name:"myName",
email:"me#email.com",
address:"x,y,z",
coordinates:{ lat:34.545, lng:78.345 }
}
res.render('myEJSfile',{data});
})
In myEJSfile.ejs file
<div id="_data" data-params="<%=data.name%>"></div>
<script>
let data = document.getElementById('_data').dataset.params;
console.log(data);
</script>
OUTPUT : myName
which is expected output
But when I try to log whole object.. Again in myEJSfile.ejs :
<div id="_data" data-params="<%=data%>"></div>
<script>
let data = document.getElementById('_data').dataset.params;
console.log(data);
</script>
OUTPUT : [object Object]
here i want to display a complete valid object passed as a parameter from server side as i need to access on each and every attribute of this object seperately
Guys im stuck i have no other way in this particular situation get me out of this
So, I'm having my data parsed to json and then put in the model attributes. Like this:
#RequestMapping("/{id}")
public String getNetworkDetails(Model model, #PathVariable String id) throws JsonProcessingException{
model.addAttribute("poolHashrates", findAndDisplayDataService.getAllPools(Long.valueOf(id)));
model.addAttribute("poolDataJson", findAndDisplayDataService.returnPoolsAsJson(Long.valueOf(id)));
return "networkDetails :: modalContents";
}
Next I'm trying to assign a poolDataJson string to a JS variable in html fragment through:
<script>
var data = eval('('+'${poolDataJson}'+')');
console.log(data);
</script>
What I would like to do with the data, is pass it to external JavaScript file as a data for my pie-chart. But first I'm getting an error on a string assignment:
Uncaught SyntaxError: Unexpected token {
What am I missing?
EDIT
I have also tried assigning json string to hidden input via:
<input type="hidden" id="networkId" th:value="${poolDataJson}"/></td>
And then read it with:
var data = document.getElementById('networkId').innerHTML;
console.log(data);
But again, nothing prints in console. When I put the ${poolDataJson} in it prints properly on a page...
You shouldn't be returning a String as JSON text. Instead, you should return regular Java objects and then evaluate it like this (thymeleaf will automatically convert objects to JSON):
<script th:inline="javascript">
var data = /*[[${poolDataJson}]]*/ {};
console.log(data);
</script>
As for your errors. I would have to guess that your method findAndDisplayDataService.returnPoolsAsJson is returning invalid JSON. Without a real example, it's hard to tell.
I'm attempting to get a JSON file into a script. I can't seem to be able to get it there by serving it from the filesystem so I made a view that returns the JSON data to the page like so:
def graph(request, d): #d.data is the file in the database
data = json.load(d.data)
return render(request, 'temp/template.html', {'json': data})
In my JS:
var j = {{ json|safe }};
When I look at the source for the JS it shows the data in this format:
{u'people': [{u'name': u'steve'}, {u'name': u'dave'}]}
Which I read shouldn't be a problem. I don't have any variables called 'id' and yet I get the error in the title pointing to the provided line of JS.
Why could this be? Also how do I then use the objects from the JSON in my script?
Solved by using simplejson:
import simplejson as json
And everything else as above. This is because the built in json.dumps returns an array of unicode like:
{u'people': [{u'name': u'steve'}, {u'name': u'dave'}]}
When using simplejson that shouldn't be a problem.
first question ever, I'm trying to parse a JSON file stored within the same file directory on my webhost as my html file that runs the javascript to parse it, I've added a console.log to debug and confrim that the file is being caught by the 'get' to ensure that I am able to 'get' the file throgh the use of jquery getJSON, in the callback i've tried to create a function that re-defines a global variable as an object containing the parsed data, but when I try to inject it into a document.getElemendtById('example').innerhtml = tgmindex.ToughGuys[1].name;
it returns a error "Uncaught TypeError: Cannot read property '1' of undefined"
here's my js/jquery
var tgmIndex;
$(document).ready(function () {
$.getJSON("http://webspace.ocad.ca/~wk12ml/test.json",function(data){
console.log( "success" );
tgmIndex =$.parseJSON;
document.getElementById('tgm1').innerHTML= tgmIndex.ToughGuys[1].name;
});
});
and here is whats contained in the JSON (i made sure to try linting it first and it's a valid json)
{"ToughGuys":[
{"name":"Ivan", "position":"Executive"},
{"name":"Little Johnny", "position":"Intern"},
{"name":"Beige Cathy", "position":"Executive"},
{"name":"Stan", "position":" original Intern"}
]}
You're setting tgmIndex to the parseJson function.
Should be doing tgmIndex =$.parseJSON(data);
Presumably your service is returning application/json. Therefore data already contains the json.
tgmIndex = data;
Then... "Tough Guys" is what you should be indexing. Not "ToughGuys"
Your example JSON is wrong in your question. If I go to
http://webspace.ocad.ca/~wk12ml/test.json
I see:
{"Tough Guys":[
{"name":"Ivan", "position":"Executive"},
{"name":"Little Johnny", "position":"Intern"},
{"name":"Beige Cathy", "position":"Executive"},
{"name":"Stan", "position":"Intern 0"}
]}
See "Tough Guys" There's your problem.
document.getElementById('tgm1').innerHTML= tgmIndex['Tough Guys'][1].name;
If data for some reason isn't JSON:
tgmIndex = $.parseJSON(data);
I'm new to angularjs and python and I have this problem. I've been trying to pass in the data of a form to Python server side using angularjs. I've converted the form to a json object before sending it over in my .js controller.
controller.js:
jsonObj = this.form.toJson;
$xhr('POST','/form/processform',jsonObj,function() {
alert("Done!");
window.load("/");
}, function(){
"Request failed";
});
Python:
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import simplejson as json
class processForm(webapp.RequestHandler):
def post(self):
form = json.loads(self.request.body)
# process forms
self.redirect("#/")#redirects to main page
I recieved an error called "JSONDecodeError: No JSON object could be decoded". I've tried to replace the 'POST' to 'JSON' but it does not seem to work as well. I've also read up on $resource in angularjs, but i'm not sure how to use it.
Is this because of the wrong usage of $xhr? Any help will be greatly appreciated! :)
Acording to JSONDecodeError the jsonObj variable is not containing a valid JSON object.
I believe problem is here:
jsonObj = this.form.toJson;
You shoud call the toJson method instead of assiging it to a variable:
jsonObj = angular.toJson(this.form);