简体   繁体   English

将 python dict 翻译成 json

[英]Translate python dict to json

I am trying with jinja2 to traverse a python dict to json.我正在尝试使用 jinja2 将 python dict 遍历到 json。 I have the following python structure我有以下python结构

examples:
   ex1: example1
   ex2: example2

With the following jinja2:使用以下 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?如果真的需要,可以调用 json 吗?

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"}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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