Home > OS >  Python read txt file and save it as json with keys
Python read txt file and save it as json with keys

Time:09-03

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

<name>:<surname>:<age>
<name>:<surname>:<age>
<name>:<surname>:<age>
<name>:<surname>:<age>
<name>:<surname>:<age>

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:

import json

with open("test.txt") as raw_data:
    for line in raw_data:
        data = line.split(":")
        print(data)

This outputs the text as follow:

["name","surname", "age"]
["name","surname", "age"]
["name","surname", "age"]
["name","surname", "age"]
["name","surname", "age"]

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:

[
{
  "Name": name,
  "Surname": surname,
  "Age": age
},
{
  "Name": name,
  "Surname": surname,
  "Age": age
},
{
  "Name": name,
  "Surname": surname,
  "Age": age
},
{
  "Name": name,
  "Surname": surname,
  "Age": age
}
]

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

CodePudding user response:

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.

import json

list_in_json = []

with open("test.txt") as raw_data:
    for line in raw_data:
        data = line.strip().split(":")
        list_in_json.append({"name": data[0], "surname": data[1], "age": data[2]})
        
print(json.dumps(list_in_json, indent=4))


[
    {
        "name": "Johnny1",
        "surname": "Boy1",
        "age": "1"
    },
    {
        "name": "Johnny2",
        "surname": "Boy2",
        "age": "2"
    },
    {
        "name": "Johnny3",
        "surname": "Boy3",
        "age": "3"
    },
    {
        "name": "Johnny4",
        "surname": "Boy4",
        "age": "4"
    },
    {
        "name": "Johnny5",
        "surname": "Boy5",
        "age": "5"
    }
]
  • Related