Skip to content
Advertisement

Python read txt file and save it as json with keys

I have a txt file that presents some data as follow:

JavaScript

The file is all structured in the same way, but I wanted to convert this file to a JSON format.

Based on my experience, I decided to go first with a split to have a list to play with:

JavaScript

This outputs the text as follow:

JavaScript

which is perfect. Here is where I get a bit confused and don’t know exactly the best approach to start working with. How can I convert that output to something like:

JavaScript

Basically I would like to create those keys and assign them the value of the list and save it as a JSON file.

Advertisement

Answer

I would do something like this which is taking each item from the the line list you’ve created and create a dictionary from them. You can append this to a list and then just use a json.dumps to convert into JSON.

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement