简体   繁体   中英

Translate python dict to json

I am trying with jinja2 to traverse a python dict to json. I have the following python structure

examples:
   ex1: example1
   ex2: example2

With the following jinja2:

examples= [{{(examples|default({}))|tojson}}]

I am achieving

   examples=[{"ex1":"example1","ex2":"example2"}]

How can i achieve

examples=[{"ex1":"example1"},{"ex2":"example2"}]

Something like

examples = {'ex1': 'example1',  'ex2': 'example2'}
out = []
for k,e in examples.items():
    out.append({k:e})
print(out)

with a call to json if really needed?

I have to put - in before my keys in order to create it as an array.

examples:
 - ex1: example1
 - ex2: example2

So now my code gives the result with two objects as below

examples=·[{"ex1":"example1"},{"ex2":"example2"}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM