从多个列表创建json文件的更好方法?

时间:2018-05-25 00:11:48

标签: python json

我有三个list,如下所示,我想从中创建一个JSON文件:

devices = ['iphone', 'ipad', 'ipod', 'watch'],
cities = ['NY', 'SFO', 'LA', 'NJ'],
companies = ['Apple', 'Samsung', 'Walmart']

我在下面做过。

首先手动创建字典:

data = {
    'devices': ['iphone', 'ipad', 'ipod', 'watch'],
    'cities': ['NY', 'SFO', 'LA', 'NJ'],
    'companies': ['Apple', 'Samsung', 'Walmart']
}

然后将其转换为JSON格式,如下所示:

import json

with open('abc.json', 'w') as outfile:
    json.dump(data, outfile, indent=4)

当我们有更多的列表时,是否有更好的方法。

理想情况下,如果我有Nlist个,我想创建一个JSON格式的文件,只需要少量的手工工作。

2 个答案:

答案 0 :(得分:1)

此方法适用于任意数量的列表,前提是它们的格式与问题中提供的格式相同。希望这会有所帮助。

# define the list vars
devices = ['iphone', 'ipad', 'ipod', 'watch'],
cities = ['NY', 'SFO', 'LA', 'NJ'],
companies = ['Apple', 'Samsung', 'Walmart']

# get the variables into a big list
v = locals()['In'][2]

output = {}

#break down the lists and turn them into dict entries
v1 = v.split(',\n')
for each in v1:
    #print(each)
    name = each.split(' = ')[0]
    data = each.split(' = ')[1]
    data = data[2:-2]
    datalist = data.split("', '")
    output[name] = datalist

#show the output
output

#export as JSON
import json

with open('C:\\abc.json', 'w') as outfile:
    json.dump(output, outfile, indent=4)

答案 1 :(得分:0)

你的问题没有显示从另一个.py文件的外部源获取list,所以这里是如何在它们被内联定义时给出它们的变量名称,如图所示:

import json

devices = ['iphone', 'ipad', 'ipod', 'watch']
cities = ['NY', 'SFO', 'LA', 'NJ']
companies = ['Apple', 'Samsung', 'Walmart']

lists = ['devices', 'cities', 'companies']

data = {listname: globals()[listname] for listname in lists}
with open('abc.json', 'w') as outfile:
    json.dump(data, outfile, indent=4)

它创建的abc.json文件的内容:

{
    "devices": [
        "iphone",
        "ipad",
        "ipod",
        "watch"
    ],
    "cities": [
        "NY",
        "SFO",
        "LA",
        "NJ"
    ],
    "companies": [
        "Apple",
        "Samsung",
        "Walmart"
    ]
}