Last active
August 17, 2018 15:42
-
-
Save vaibhavhrt/64230110ba0a4d8a186681c4512e0f0c to your computer and use it in GitHub Desktop.
[Python] Get json string from a python dict containing one or more list of strings into json, all list must be of same size
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" Get json string from a python dict containing lists of same size, see example at bottom of code """ | |
import pyperclip | |
def dict_to_json(lists, cont=False, start_from=0): | |
""" convert a list of strings to json """ | |
if cont: | |
json = '' | |
else: | |
json = '{\n' | |
keys = [] | |
for key in lists.items(): | |
keys.append(key[0]) | |
for i in range(0, len(lists[keys[0]])): | |
json += '\t"'+str(i+start_from)+'": {\n\t\t"id": "'+str(i+start_from)+'",\n' | |
for j in range(0, len(keys)): | |
if j < len(keys)-1: | |
json += '\t\t"'+keys[j]+'": "'+lists[keys[j]][i]+'",\n' | |
else: | |
json += '\t\t"'+keys[j]+'": "'+lists[keys[j]][i]+'"' | |
json += '\n\t},\n' | |
if not cont: | |
json = json[:-2] | |
json += '\n}' | |
else: | |
json += '\t' | |
return json | |
# EXAMPLE | |
# dictionary can have any number of lists as long as they are of same size | |
MY_DICT = { | |
"country": ["Afghanistan", "Albania", "Algeria",], | |
"country_code": ["93", "355", "213",], | |
"ISO_code": ["AF / AFG", "AL / ALB", "DZ / DZA",], | |
} | |
pyperclip.copy(dict_to_json(MY_DICT)) | |
# see output string below, ready to be pasted into a json file |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"0": { | |
"id": "0", | |
"country": "Afghanistan", | |
"country_code": "93", | |
"ISO_code": "AF / AFG" | |
}, | |
"1": { | |
"id": "1", | |
"country": "Albania", | |
"country_code": "355", | |
"ISO_code": "AL / ALB" | |
}, | |
"2": { | |
"id": "2", | |
"country": "Algeria", | |
"country_code": "213", | |
"ISO_code": "DZ / DZA" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment