繁体   English   中英

如何在Python列表中制作JSON文件?

[英]How do I make a JSON file out of a list in Python?

我尝试制作一个看起来像这样的有效JSON文件:

{
    "video": [
      {"title": "New", "id": "123"},
      {"title": "New", "id": "123"}
    ]
  }

在两个包含标题和ID的列表中。

titles = ['New', 'New']
ids = ['123', '123']

我尝试了和for循环

key[] = value

但这仅给了我最后两项。

我也尝试过

newids = {key:value for key, value in titles}

这也行不通。

有人可以给我建议怎么做吗?

使用zip()配对列表:

{'video': [{'title': title, 'id': id} for title, id in zip(titles, ids)]}

video值由列表推导形成; 对于每个title, idzip()组成的title, id对将创建一个字典:

>>> titles = ['New', 'New']
>>> ids = ['123', '123']
>>> {'video': [{'title': title, 'id': id} for title, id in zip(titles, ids)]}
{'video': [{'title': 'New', 'id': '123'}, {'title': 'New', 'id': '123'}]}

或更有趣的内容:

>>> from pprint import pprint
>>> titles = ['Foo de Bar', 'Bring us a Shrubbery!', 'The airspeed of a laden swallow']
>>> ids = ['42', '81', '3.14']
>>> pprint({'video': [{'title': title, 'id': id} for title, id in zip(titles, ids)]})
{'video': [{'id': '42', 'title': 'Foo de Bar'},
           {'id': '81', 'title': 'Bring us a Shrubbery!'},
           {'id': '3.14', 'title': 'The airspeed of a laden swallow'}]}

如果您还不知道如何使用json将结果编码为JSON,以使用以下方法写入文件:

import json

with open('output_filename.json', 'w', encoding='utf8') as output:
    json.dump(python_object, output)

暂无
暂无

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

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