Flask: python object to json triggering error when read by javascript - javascript

I'm trying to pass python dictionaries and javascript objects back and forth as necessary. From similar questions, I've gathered that I need to do this.
Python:
posts = [
{'author':'JL Rowling','title':'Harry Potter'},
{'author':'JRR Tolkien','title':'Lord of the Rings'},
]
Javascript:
var jsonPosts = JSON.parse({{ posts }});
console.log(jsonPosts);
Likewise, these doesn't work either:
var jsonPosts = JSON.parse(posts|tojson);
var jsonPosts = {{ posts|tojson }};
The JS error I'm triggering is TypeError: Object of type Undefined is not JSON serializable
I got this advice from the following Q/A:
Python to Javascript JSON objects (Flask)
How can I pass data from Flask to JavaScript in a template?
How can I fix this?
Edit:
I've used answer recommendation and found the following error to be present in the console:
VM129:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at about:16
Corresponding to
let jsonPosts = JSON.parse();
It seems that it doesn't have access to encoded_posts.

You need to use the encoded posts:
encoded_posts = json.dumps(posts)
That will give you string, which is what JSON.parse is expecting.
var jsonPosts = JSON.parse({{ encoded_posts }});

Related

Access JSON object from another file in Javascript

Perhaps a simple question but I am still new to JS / nodeJS.
I have a script that is doing some basic string matching (dict.js), and I am trying to access a JSON formatted object from another file (words.json) to iterate through.
The directory structure looks like:
scratch
- algorithms
- dict.js
- utilities
- words.json
The contents of the files are:
words.json
{"a": 1,"aa": 1,"aaa": 1,"aah": 1,"aahed": 1,"aahing": 1,"aahs": 1,"aal": 1}
dict.js
decode (password) {
const jsonData = require('../utilities/words.json');
myObj = JSON.parse(jsonData);
for (const x in myObj) {
console.log(x)
// compare password against item in words.json
}
console.log(Object.keys(myObj).length)
return "stub";
}
I am getting an error in developer tools when I create a block (this is the backend to a block in Scratch) that uses this Decode function.
Uncaught SyntaxError: Unexpected token o in JSON at position 1
Thanks
In nodejs environment you can directly import json file data without parsing it. For exaple:
const myObj = require('../utilities/words');
This gives you the data in your json file as a ready-to-go object.
In your case, you are trying to parse json object with JSON.parse() which expects stringified json. So just remove the part JSON.parse(jsonData);

How to fix frontend javascript in handlebars catching undefined value from server?

I have a JSON object in backend which I want to send to frontend javascript. But I'm constantly encountering "undefined" when trying to access that variable.
candidates is json object and is working fine in server side.
Here's my server side code.
res.render('electionview',{title: 'Election', poll: poll, data: JSON.stringify(candidates) });
Here's my script in Handlebars
<script type="text/javascript">
var candidates = {{{data}}};
console.log(candidates);
<script>
But I'm getting this error in console.
Uncaught SyntaxError: Unexpected token ';'
When I remove semicolon, output in the console is undefined. What am I missing ?
Server-side:
let obj = {};
obj.title = 'Election';
obj.poll = poll;
obj.data = candidates;
res.render('electionview', obj);
I'm assuming that the render function already knows how to serve objects as JSON, so no need to JSON.stringify anything.
Then, on the client-side, JSON.parse() the object above in whole. After that, it should have a data property that you can use as needed.
I was getting candidates as:
Candidate.find({}).lean()
.then(candidates=>res.render("electionview", JSON.stringify(candidates))
Removing .lean() fixed it.

how to solve problem getting json object element

I have a json object that i want to use.
{
"type": "PROVIDER_PAYLOAD",
"message": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVkOTQ3OTg4N2RlMGRkMDc4ZjEzM2FmNyIsImVtYWlsIjoiYWxzb25nZHVuc3RhbjJAZ21haWwuY29tIiwicm9sZSI6IkNVU1RPTUVSIiwiaWF0IjoxNTcwMDI3MDA4fQ.FcpoBPmhTSX535bNgE2ezCCWsNFPjEhc87hM4y6WadM"
}
so when i try to access it using
console.log("Postback: " + payload.type)
but i get an error of
Postback: undefined
i have looked over some resources on the web and most of them do it this way and it works but i am not sure why mine is not giving the value for type
thanks in advance
Subh is right. You have to parse the JSON into an object before accessing type using payload.type syntax.
So, let's say you have the following:
let payload = {
"type": "PROVIDER_PAYLOAD",
"message": "eyJhbGciOiJIUzWadM"
}
You have to convert it into a JS object using JSON.parse:
let payloadObj = JSON.parse(payload);
Now, if you do payloadObj.type, you should be fine.
console.log(payloadObj.type); // PROVIDER_PAYLOAD
It should work fine.
UPDATE: ERROR: SyntaxError: Unexpected token a in JSON at position 0
If you are getting this error, try following to Parse the payload.
let payloadObj = JSON.parse(JSON.stringify(payload))
It should solve the problem for you.

Javascript - Read JSON fields that are formatted as urls

A REST API sends me JSON back with URLs as fields.
How do I read these fields with Javascript?
This doesn't work...
var json = JSON.parse(profile);
console.log(json["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality"]);
Error:
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at Strategy._verify (D:\Development\NodeJS\EID_TEST_NODEJS\server.js:33:21)
at validateCallback (D:\Development\NodeJS\EID_TEST_NODEJS\node_modules\passport-saml\lib\passport-saml\strategy.js:61:14)
at D:\Development\NodeJS\EID_TEST_NODEJS\node_modules\passport-saml\lib\passport-saml\saml.js:845:5
at _fulfilled (D:\Development\NodeJS\EID_TEST_NODEJS\node_modules\q\q.js:854:54)
at self.promiseDispatch.done (D:\Development\NodeJS\EID_TEST_NODEJS\node_modules\q\q.js:883:30)
at Promise.promise.promiseDispatch (D:\Development\NodeJS\EID_TEST_NODEJS\node_modules\q\q.js:816:13)
at D:\Development\NodeJS\EID_TEST_NODEJS\node_modules\q\q.js:624:44
at runSingle (D:\Development\NodeJS\EID_TEST_NODEJS\node_modules\q\q.js:137:13)
at flush (D:\Development\NodeJS\EID_TEST_NODEJS\node_modules\q\q.js:125:13)
JSON send back from the api:
{
"issuer":"www.econtract.be",
"nameID":"00081007501",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality":"Hasselt",
"be:fedict:eid:idp:card-validity:end":"2023-03-03T00:00:00Z",
"be:fedict:eid:idp:card-number":"592548451825",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier":"00081007501",
"be:fedict:eid:idp:nationality":"Belg",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dateofbirth":"2000-08-10T00:00:00Z",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/gender":"1",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/postalcode":"3511",
etc....
}
Problem solved! Thanks #Mike
Change this code:
var json = JSON.parse(profile);
console.log(json["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality"]);
To this code:
console.log(profile["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality"]);
Thanks for the help!
Observation :
You are trying to parse JSON Object. No need to parse JSON object again as it is already parsed while sending back from the API.
Working Demo
var profile = {
"issuer":"www.econtract.be",
"nameID":"00081007501",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality":"Hasselt",
"be:fedict:eid:idp:card-validity:end":"2023-03-03T00:00:00Z",
"be:fedict:eid:idp:card-number":"592548451825",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier":"00081007501",
"be:fedict:eid:idp:nationality":"Belg",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dateofbirth":"2000-08-10T00:00:00Z",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/gender":"1",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/postalcode":"3511"
};
console.log(profile["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality"]);

Result of BsonDocument.ToJson fails when used in JSON.parse

I'm retrieving data from MongoDB and then sending it to client:
var bsonDocument = ... retrieve from database ...
var dto = new Dto { MyBson = bsonDocument.ToJson() };
On the client I'm trying to parse MyBson property using JSON.parse.
I'm getting the following error: SyntaxError: Unexpected token N. I guess this is because one of the properties looks like this:
{ ..., "SomeIntProp" : NumberLong(70) }
JavaScript parser simply doesn't understand Bson data type: NumberLong.
How should I convert BsonDocument to JSON so that the output would omit NumberLong?
There is no easy way to solve this, I worked out a solution by writing my own parsing function which understands the MongoDB BSON types and does the conversion. The native JSON.parse only understands the types used by the JavaScript. Here is my version:
https://gist.github.com/Hrish2006/8270187
You probably will not need the html snippets in the code.

Categories