Ehab Reda
Ehab Reda

Reputation: 60

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:

{
    "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.

Upvotes: 2

Views: 245

Answers (3)

yaputra jordi
yaputra jordi

Reputation: 523

You can use regex to capture groups then rearrange the word.

import json
import re

filename = 'data_quality/quality-2021-11-21_12-10-21.908466.txt'
dict1 = {}
with open(filename) as fh:
    for line in fh:
        name, percent = re.findall("SSID: ([^,]*), quality: (\d+)%", line.strip())[0]
        dict1[f"{name}, quality"] = f"{percent}%"
# ...

Upvotes: 1

Marya
Marya

Reputation: 180

import json
filename = 'test.txt'
dict1 = {}
with open(filename) as fh:
    for line in fh:
        line = line.replace('SSID: ','')
        command, description = line.strip().split(None, 1)
        dict1[command] = description.strip()
print(dict1)
out_file = open("testooo.json", "w")
json.dump(dict1, out_file, indent=4, sort_keys = False)
out_file.close()

Upvotes: 0

Barmar
Barmar

Reputation: 780842

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)

Upvotes: 3

Related Questions