运行环境: Python3.10 Fastapi 0.95 Jinja 3.1.2 PostgreSQL
问题: PostgreSQL数据表中有一个text类型的字段,存储的是一段 json 格式的字符串,如下:
```html
{ "1": {
"id": "1",
"name": "菜鸟教程",
"url": "www.runoob.com"
},
"2": {
"id": "2",
"name": "菜鸟工具",
"url": "c.runoob.com"
},
"3":{
"id": "3",
"name": "谷歌",
"url": "www.google.com"
}
}
我想在jinja 3.X的模板中取出id为1的 Json数据并显示出来。
d1为一个条完整的记录, text为其中存储json字符串的字段。
使用
{% set strt = d1.text |safe %}
{{strt}} 则输出:
```html
{ "1": {
"id": "1",
"name": "菜鸟教程",
"url": "www.runoob.com"
},
"2": {
"id": "2",
"name": "菜鸟工具",
"url": "c.runoob.com"
},
"3":{
"id": "3",
"name": "Google",
"url": "www.google.com"
}
}
使用
{% set strt = d1.text |safe %}
{{strt |tojson}} 则输出如下,:
"{ \"1\": {\n \"id\": \"1\",\n \"name\": \"\u83dc\u9e1f\u6559\u7a0b\",\n \"url\": \"www.runoob.com\"\n },\n \"2\": {\n \"id\": \"2\",\n \"name\": \"\u83dc\u9e1f\u5de5\u5177\",\n \"url\": \"c.runoob.com\"\n },\n \"3\":{\n \"id\": \"3\",\n \"name\": \"Google\",\n \"url\": \"www.google.com\"\n }\n}"
请问应该要用什么jinja 3.X的模板语法才能取出 key为 1 的value? 谢谢
text属性是字符串,后端python代码用json模块json字符串转对象后字典1的键值后再赋值给模板,示例大概如下
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
import json
import uvicorn
app = FastAPI() # 实例化 FastAPI对象
templates = Jinja2Templates(directory="templates") # 实例化Jinja2对象,并将文件夹路径设置为以templates命令的文件夹
@app.get('/')
def idnex(request: Request):
############################改为d1.text,这里测试直接写死字符串了
text='''{ "1": {
"id": "1",
"name": "菜鸟教程",
"url": "www.runoob.com"
},
"2": {
"id": "2",
"name": "菜鸟工具",
"url": "c.runoob.com"
},
"3":{
"id": "3",
"name": "谷歌",
"url": "www.google.com"
}
}'''
value=json.loads(text).get("1")
return templates.TemplateResponse(
'index.html',
{
'request': request,
'value':value
}
)
uvicorn.run(app, host="127.0.0.1", port=8000)
index.html
<meta charset="utf-8" />
{{value.get('id')|safe}}
<br />
{{value.get('name')|safe}}
<br />
{{value.get('url')|safe}}
谢谢指点。
我的需求场景是:数据库有100条数据记录,每条数据记录都包含一个text字段,存储着不同数量的键值对(json格式)。
我想循环显示所有数据记录内的text字段的键值对。
我想在jinja 模板里边实现类似以下的逻辑:
for record in records: #从数据库中取出所有符合条件的记录
jsonString = json.load( record["text"] ) : #从每条记录中取出json字符串,并转换为json对象
for k1,v1 in jsonString : #从json对象中循环取出所有的键值对并打印
print(k1,v1) #打印单个键值对
jinja语法不能处理json对象吗? 那么 jinja2里边的 tojson 的过滤器有什么作用呢?
请问应该怎么实现才行呢?谢谢