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.

jbuddy_13
  • 902
  • 2
  • 12
  • 34

1 Answers1

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 }});
Jim Wright
  • 5,905
  • 1
  • 15
  • 34