Last active
May 5, 2023 23:21
-
-
Save NonymousMorlock/86ede13fbd97d3eeade78a6748623233 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import json | |
import re | |
import sys | |
class Colour: | |
HEADER = '\033[95m' | |
OKBLUE = '\033[94m' | |
OKCYAN = '\033[96m' | |
OKGREEN = '\033[92m' | |
WARNING = '\033[93m' | |
FAIL = '\033[91m' | |
ENDC = '\033[0m' | |
BOLD = '\033[1m' | |
UNDERLINE = '\033[4m' | |
def quoteIsolatedString(string): | |
is_word = False | |
word_start = 0 | |
new_string = string | |
for i, c in enumerate(string): | |
if c.isalpha(): | |
if not is_word: | |
word_start = i | |
is_word = True | |
elif is_word: | |
if string[word_start - 1] not in ['"', "'"] and string[i] != '(': | |
new_string = string[:word_start] + '"' + string[word_start:i] + '"' + string[i:] | |
return quoteIsolatedString(new_string) | |
is_word = False | |
return new_string | |
is_class = False | |
def convertToProperJson(): | |
global is_class | |
is_class = input("Is this a class? (y/n): ").lower() == 'y' | |
print(f'Paste your string below and press {Colour.OKGREEN}Ctrl + D{Colour.ENDC} to convert it to proper JSON') | |
string = sys.stdin.read() | |
if not is_class: | |
# Add double quotes to keys | |
string = re.sub(r'(\s*)(\w+)(\s*:\s*)', r'\1"\2"\3', string) | |
# Add double quotes to values that start with alphabets | |
string = re.sub(r'(\s*:\s*)([a-zA-Z]\w*)(\s*,|\s*})', r'\1"\2"\3', string) | |
# Find and quote any remaining unquoted strings | |
string = quoteIsolatedString(string) | |
# Remove trailing commas | |
string = re.sub(r',(\s*[}\]])', r'\1', string) | |
if is_class: | |
# remove the quotes from the keys | |
string = re.sub(r'(\s*)"(\w+)"(\s*:\s*)', r'\1\2\3', string) | |
return string | |
else: | |
return json.dumps(json.loads(string), indent=4, separators=(',', ':')) | |
final_string = convertToProperJson() | |
extension = '.txt' if is_class else '.json' | |
with open(f'formattedData.{extension}', 'w') as f: | |
f.write(final_string) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment