【问题标题】:render json data with newlines flask/jinja2使用换行符 flask/jinja2 渲染 json 数据
【发布时间】:2018-05-21 17:05:29
【问题描述】:

我希望烧瓶使用包含换行符的 json 呈现模板。但是,JSON.parse() 会引发错误。我想找到处理此类信息的最佳方式。

迷你示例应用程序:

from flask import Flask, render_template_string
import json

app = Flask(__name__)

@app.route('/')
def index():
    example = {'blabla': 'what\'s up\n\nnot much'}
    return render_template_string('''<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>title</title>
</head>
<body>
<script>
JSON.parse('{{ some_json_data | tojson }}')
</script>
</body>
</html>
''', some_json_data=example)

到目前为止我尝试过的组合:

example = {'blabla': 'oh no\n\n'}
JSON.parse('{{ some_json_data | tojson }}')
SyntaxError: JSON.parse: bad control character in string literal at line 1 column 22 of the JSON data

example = {'blabla': 'oh no\n\n'}
JSON.parse('{{ some_json_data | tojson(indent=4) }}')
SyntaxError: '' string literal contains an unescaped line break


example = json.dumps({'blabla': 'what\'s up\n\nnot much'})
JSON.parse('{{ some_json_data }}')
SyntaxError: JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data

example = json.dumps({'blabla': 'what\'s up\n\nnot much'})
JSON.parse('{{ some_json_data | safe }}')
SyntaxError: missing ) after argument list

【问题讨论】:

    标签: json flask jinja2


    【解决方案1】:

    在写这个问题时,我尝试了更多的组合,并找到了一个有效的组合。

    example = json.dumps({'blabla': 'what\'s up\n\nnot much'})
    JSON.parse({{ some_json_data | tojson }})
    

    【讨论】:

      猜你喜欢
      • 2018-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-23
      • 1970-01-01
      相关资源
      最近更新 更多