Make custom file format a json file

121 Views Asked by At

I'm trying to convert a custom file to JSON for easy editing. Here is the custom code example:

{
    "#letter_a" "A"
    "#letter_b" "B"
    "#letter_c" "C"
    "#letter_d" "D"
    "#letter_e" "E"
    "#letter_f" "F"
    "#letter_g" "G"
    "#letter_h" "H"
    "#letter_i" "I"
    "#letter_j" "J"
    "#letter_k" "K"
    "#letter_l" "L"
    "#letter_m" "M"
}

I need to add ':' at the end of keys then add ',' at the end of the line. Here is the code i tried:

import in_place

with in_place.InPlace('english_m.lang', encoding="utf-8", backup='.bak') as file:
    for line in file:
        cumle = line.join(line.split('"', 2)[:2])
        print(line.replace(cumle, cumle+'":'), end='')

It didn't quite work, it always delete all the lines in the file.

How can i solve this problem or is there any way to just convert this file format to JSON?

2

There are 2 best solutions below

2
Mark Ransom On

in_place is designed to replace the original content with new content you write to the file. Your code has no write calls in it, so you end up with an empty file.

0
dermen On

You should try your parsing commands on dummie example lines and see that they work / dont work. I wont do that here, but Ill show you an example that will hopefully help you along.

Here is how you can convert your file in place to something almost JSON

with in_place.InPlace("english_lang.txt",encoding="utf-8", backup=".bak" ) as file:
    for line in file:
        try:
            items = [item.strip() for item in line.split()]
            assert len(items)==2
            line = " " + items[0] +": "+ items[1]+",\n"
        except: 
            pass
        file.write(line)

Content of english_lang.txt is now

{
 "#letter_a": "A",
 "#letter_b": "B",
 "#letter_c": "C",
 "#letter_d": "D",
 "#letter_e": "E",
 "#letter_f": "F",
 "#letter_g": "G",
 "#letter_h": "H",
 "#letter_i": "I",
 "#letter_j": "J",
 "#letter_k": "K",
 "#letter_l": "L",
 "#letter_m": "M",
}

Its not a JSON because of the trailing comma after the last dictionary entry.

You can still load it using ast

import ast
D = ast.literal_eval(open("english_lang.txt", "r").read())
# you can save this to json using json.dump , but that defeats the purpose of in_place

If you want to make an english_lang.txt in-place that can be loaded via json e.g. D = json.load(open("english_lang.txt", "r")), then you need to make a more sophisticated version of the in_place editor code shown above; specifically one that removes the last comma after "M".