Template in jinja2 batch replaces content in json string

Elasticsearch is used in the project, and the query method in Json format is used. There are several places in a query statement that need to be replaced, and the replaced values ​​are the same. At first, I converted json to string and processed it with the format function. I found that it could not be successfully converted back to json. My colleagues reminded that you can use jinja2 template to process strings.

second_search = """

    {
"query": {
"bool": {
"should": [
{
"bool": {
"should": [
{
"term": {
"{{ prod }}_name_en.text": {
"value": "{{ keyword }}",
"boost": 10
}
}
},
{
"term": {
"{{prod}}_name_zh.text": {
"value": "{{ keyword }}",
"boost": 10
}
}
}
]
}
},
{
"bool": {
"should": [
{
"wildcard": {
"{{prod}}_name_en.text": {
"value": "{{ keyword }}*",
"boost": 5
}
}
},
{
"wildcard": {
"{{prod}}_name_zh.text": {
"value":"{{ keyword }}*",
"boost": 5
}
}
}
]
}
},
{
"query_string": {
"fields": ["{{prod}}_name_en", "{{prod}}_name_zh"],
"query": "{{ keyword }}",
"boost": 1
}
}
]
}
}
}
"""
second_tpl = Template(second_search)
second_str = second_tpl.render(keyword=kws, prod='other')
second_json = json.loads(second_str)
经过这么处理后再把字符串转为json对象很顺利

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325250067&siteId=291194637