4

I have a json string stored in the database and when this is pulled out and shown on the template it is a string. I want to convert this into a dict object so I can access the contents directly.

string = "{'a':1, 'b':3}"

{{ obj }} ---> string "{'a':1, 'b':3}"

{{ obj.b }} ---> I want to access it like an object.

user299709
  • 4,922
  • 10
  • 56
  • 88

2 Answers2

2
obj_in_string = "{'a':1, 'b':3}"
{{ obj_in_string | tojson }} 

Ref: https://jinja.palletsprojects.com/en/3.0.x/templates/#jinja-filters.tojson

Suicide Bunny
  • 894
  • 1
  • 10
  • 23
-6

Write the following code in a temporary file and write a function back-end side:

{{ obj.b | str_to_obj }}

Put this code in your jinja filter file:

for convert str to dic object 

def str_to_obj(str):

    return eval(str)

And write this code in your admin file:

app.jinja_env.filters['str_to_obj'] = jinja_filters.str_to_obj
Michaël Azevedo
  • 3,874
  • 7
  • 31
  • 45
Suraj
  • 170
  • 5
  • eval() is considered bad programming practice because it allows users to dynamically execute arbitrary Python code, hence the down votes. See https://stackoverflow.com/questions/1832940 – frainfreeze Jan 18 '21 at 13:19