Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert text file to JSON in python?

I have text files that include this data:

SSID: Wudi, quality: 86%
SSID: Vodafone_ADSL_2018, quality: 92%
SSID: Akram, quality: 43%
SSID: WE_BAE8DF, quality: 31%
SSID: BlzS-b21hcjE5MjE5OTg, quality: 31%
SSID: OPPO A53, quality: 31%
SSID: Vodafone_ADSL_2018, quality: 92%
SSID: WIFI 1, quality: 87%
SSID: , quality: 31%
SSID: pretty angel, quality: 31%
SSID: NETGEAR, quality: 84%
SSID: Akram, quality: 40%
SSID: memo, quality: 85%
SSID: Wudi, quality: 86%
SSID: AndroidAP63FC, quality: 38%

So I want to convert my text file to JSON. I have tried this code:

import json
filename = 'data_quality/quality-2021-11-21_12-10-21.908466.txt'
dict1 = {}
with open(filename) as fh:
    for line in fh:
        command, description = line.strip().split(None, 1)
        dict1[command] = description.strip()

out_file = open("testooo.json", "w")
json.dump(dict1, out_file, indent=4, sort_keys = False)
out_file.close()

but it gives me the file in that format:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
    "SSID:": "AndroidAP63FC, quality: 38%"
}

but I need the file to be formatted like that:
first, delete the "SSID" then it becomes

{
   "AndroidAP63FC, quality": "38%",
   "Wudi, quality": "86%",
   "Vodafone_ADSL_2018, quality:" "92%",
   and so on...
}

Note: I have more than 1000 files so I want to do it with code.

>Solution :

Use colon as the split() delimiter, then use the 2nd element as the key and third element as the value:

import json
filename = 'data_quality/quality-2021-11-21_12-10-21.908466.txt'
dict1 = {}
with open(filename) as fh:
    for line in fh:
        _, command, description = line.strip().split(':')
        dict1[command.strip()] = description.strip()

with open("testooo.json", "w") as out_file:
    json.dump(dict1, out_file, indent=4, sort_keys = False)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading