简体   繁体   English

如何从python中的多个列表创建JSON格式的字符串?

[英]How to create JSON formatted string from multiple lists in python?

I have 3 lists, 我有3个清单,

city_id = [1,2,3]
city_name = ['a','b','c']
city_capital = ['x','y','z']

How to combine the above three lists into a json in the below format without iterating over by myself. 如何将以下三个列表组合成以下格式的json,而无需自己进行迭代。 Is there any library function available in python to get the job done? python中有可用的库函数来完成这项工作吗?

[
    {
        'city_id': 1,
        'city_name': 'a',
        'city_capital': 'x'
    },
    {
        'city_id': 2,
        'city_name': 'b',
        'city_capital': 'y'
    },
    {
        'city_id': 3,
        'city_name': 'c',
        'city_capital': 'z'
    }
]

To get a list with data in that form: 要获取包含该格式数据的列表:

[ { 'city_id': x, 'city_name': y, 'city_capital': z } 
  for x, y, z in zip(city_id, city_name, city_capital) ]

If you want to output the data in exactly that form, then you can use the suggestion by @AndyKubiak in the comments: 如果你想输出正是表单中的数据,那么你可以使用@AndyKubiak建议的评论:

import json
d = [ { 'city_id': x, 'city_name': y, 'city_capital': z } 
      for x, y, z in zip(city_id, city_name, city_capital) ]
pretty_json = json.dumps(d, sort_keys=True, indent=4)

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

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