User12345
User12345

Reputation: 5480

Better way to create json file from multiple lists?

I have three lists like below and I want to create a JSON file from them:

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

I have done like below.

First manually create a dictionary:

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

Then convert it to JSON format like this:

import json

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

Is there a better way of doing this when we have more number of lists.

Ideally if I have N number of lists, I want to create a JSON formatted file a minimal amount of manual work.

Upvotes: 1

Views: 7818

Answers (2)

martineau
martineau

Reputation: 123423

Your question doesn't show getting the lists from an external source like another .py file, so here's how to do it given their variable names when they've been defined in-line as shown in it:

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)

Contents of the abc.json file it creates:

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

Upvotes: 2

Worm
Worm

Reputation: 1431

This method will work for any number of lists providing they have the same format as the ones provided in your question. Hope this helps.

# 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)

Upvotes: 1

Related Questions