How to pass JSON with newline \n from flask backend to Jinja2 and JQuery frontend?

45 views Asked by At

I am trying to pass an array of dictionaries contain escape characters from my flask backend to Jinja2 with JS.

'[{"id": 3, "tags": "t2", "content": "B"}, {"id": 5, "tags": "t3", "content": "C,\\nD"}]'

I create it with

    contents = Content.query.all()
    contents_list = [content.to_dict() for content in contents]
    contents_json = json.dumps(contents_list)

I then pass contents_json forward. from a database

Database screenshot

without the \n it works fine.

'[{"id": 3, "tags": "t2", "content": "B"}, {"id": 5, "tags": "t3", "content": "C,D"}]'

but with the newline I get:

Uncaught SyntaxError: JSON.parse: bad control character in string literal at line 1 column 81 of the JSON data http://127.0.0.1:5000/:25 jQuery 13 e t setTimeout handlerDeferred/then/l/< c fireWith fire c fireWith ready q EventListener.handleEvent 127.0.0.1:5000:25:23

I've tried

  var contents = JSON.parse('{{ contents_json |tojson| safe }}');

and

  var contents = JSON.parse('{{ contents_json | safe }}');

I'm looking for a fix that will work with many different special characters because content will have markdown formatting characters.

1

There are 1 answers

0
OrigamiEye On

It works now with

@app.route('/', methods=["GET"])
def home():
    contents = Content.query.all()
    contents_list = []
    for content in contents:
        content_dict = content.to_dict() 
        if 'content' in content_dict:
            content_dict['content'] = content_dict['content'].replace("\n", "\\n")
        contents_list.append(content_dict)

    return render_template("editClick.html", contents_json=contents_list)

Then in the Jinja template

  var contents = JSON.parse('{{ contents_list| tojson |safe }}');

It was Python escaping the \n that was causing the issue.