-1

I received a file which contains key and unquoted values which looks like a json file but is not valid due to unquoted keys and values.

Is there an existing module in python that will be able to load this and clean it as a valid json file?

sample.txt

{
 apple: [green,red],
 kiwi: [green,gold],
 strawberry: red
}
mtryingtocode
  • 939
  • 3
  • 13
  • 26

1 Answers1

2

Solution is described on How to turn a string with unquoted keys into a dict in Python

In your case code should be:

class identdict(dict):
    def __missing__(self, key):
        return key

dict_file = open('sample.txt')

uq_dict = dict_file.read()
real_dict = eval(uq_dict, identdict())

print(real_dict)
print(real_dict['kiwi'][1])
adobro
  • 21
  • 4