0

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.

1 Answer 1

0

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 }});
Sign up to request clarification or add additional context in comments.

1 Comment

I tried this to no success. So I troubleshooted the JSON and the issue seems to be there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.