How to convert a text file to json file? - python

I have this ".txt" file image so I want to convert it to a JSON file using python
I've tried a lot of solutions but It didn't work because of the format of the file.
can anyone help me, please!
can I convert it so it will be easy to manipulate it?
This is my file
Teste: 89
IGUAL
{
"3C:67:8C:E7:F5:C8": ["b''", "-83"],
"64:23:15:3D:25:FC": ["b'HUAWEI-B311-25FC'", "-83"],
"98:00:6A:1D:6F:CA": ["b'WE'", "-83"],
"64:23:15:3D:25:FF": ["b''", "-83"],
"D4:6B:A6:C7:36:24": ["b'Wudi'", "-51"],
"00:1E:2A:1B:A5:74": ["b'NETGEAR'", "-54"],
"3C:67:8C:63:70:54": ["b'Vodafone_ADSL_2018'", "-33"],
"90:F6:52:67:EA:EE": ["b'Akram'", "-80"],
"04:C0:6F:1F:07:40": ["b'memo'", "-60"],
"80:7D:14:5F:A7:FC": ["b'WIFI 1'", "-49"]
}
and this is the code I tried
import json
filename = 'data_strength/dbm-2021-11-21_12-11-47.963190.txt'
dict1 = {}
with open(filename) as fh:
for line in fh:
command, description = line.strip().split(None, 10)
dict1[command] = description.strip()
out_file = open('test1.json', "w")
json.dump(dict1, out_file, indent=4, sort_key=False)
out_file.close()

The JSON structure in your file starts at the first occurrence of a left brace. Therefore, you can just do this:
import json
INPUT = 'igual.txt'
OUTPUT = 'igual.json'
with open(INPUT) as igual:
contents = igual.read()
if (idx := contents.find('{')) >= 0:
d = json.loads(contents[idx:])
with open(OUTPUT, 'w') as jout:
json.dump(d, jout, indent=4)

Related

json dump not updating the file

I wanted to store some value in a json file
json file gets readed but not getting writed
import json
import os
filepath = os.path.abspath(__file__).replace("test.py", "test.json")
data = json.load(open(filepath, "r"))
out_file = open("test.json", "w")
a = input()
data["cool"] = a
print(data)
json.dump(data,out_file, indent = 6)
out_file.close()

How can I edit my code to print out the content of my created json file?

My program takes a csv file as input and writes it as an output file in json format. On the final line, I use the print command to output the contents of the json format file to the screen. However, it does not print out the json file contents and I don't understand why.
Here is my code that I have so far:
import csv
import json
def jsonformat(infile,outfile):
contents = {}
csvfile = open(infile, 'r')
reader = csvfile.read()
for m in reader:
key = m['No']
contents[key] = m
jsonfile = open(outfile, 'w')
jsonfile.write(json.dumps(contents))
csvfile.close()
jsonfile.close()
return jsonfile
infile = 'orders.csv'
outfile = 'orders.json'
output = jsonformat(infile,outfile)
print(output)
Your function returns the jsonfile variable, which is a file.
Try adding this:
jsonfile.close()
with open(outfile, 'r') as file:
return file.read()
Your function returns a file handle to the file jsonfile that you then print. Instead, return the contents that you wrote to that file. Since you opened the file in w mode, any previous contents are removed before writing the new contents, so the contents of your file are going to be whatever you just wrote to it.
In your function, do:
def jsonformat(infile,outfile):
...
# Instead of this:
# jsonfile.write(json.dumps(contents))
# do this:
json_contents = json.dumps(contents, indent=4) # indent=4 to pretty-print
jsonfile.write(json_contents)
...
return json_contents
Aside from that, you aren't reading the CSV file the correct way. If your file has a header, you can use csv.DictReader to read each row as a dictionary. Then, you'll be able to use for m in reader: key = m['No']. Change reader = csvfile.read() to reader = csv.DictReader(csvfile)
As of now, reader is a string that contains all the contents of your file. for m in reader makes m each character in this string, and you cannot access the "No" key on a character.
a_file = open("sample.json", "r")
a_json = json.load(a_file)
pretty_json = json.dumps(a_json, indent=4)
a_file.close()
print(pretty_json)
Using this sample to print the contents of your json file. Have a good day.

Save data in JSON file

I am missing something in below code, not able to save in correct format, Can you please guide where I'm going wrong...
Python Code
str_next_thursday_expiry = 23JUL2020
f = open("data/expiry.json","r")
with open("data/expiry.json", "w") as f:
json.dump(str_next_thursday_expiry, f)
Output in expiy.json
"23JUL2020"
I want to store this in below format, not getting what needs to be corrected..
{"expirydate": "23JUL2020"}
str_next_thursday_expiry = "23JUL2020"
with open("data/expiry.json", "w") as f:
data = {"expirydate":str_next_thursday_expiry}
json.dump(data, f)
try this
content = {"expirydate": "23JUL2020"}
with open("data/expiry.json", "w") as f:
json.dump(str_next_thursday_expiry, f)

How to get corresponding output text file for each input file,while extracting data from json file.?

I have written a script in python, which works on a multiple file,but ouput I am getting in one file. I want to get output for each file separately.
import json
import os
files = os.listdir('C:/Users/123456/Desktop/Ten sample /Ten sample ')# path_to_json
for FILE in files:
if FILE.endswith('.json'):
with open(FILE) as json_data:
data = json.load(json_data)
for r in (data['elements']): #print(r['types'], r['categories'])
for t in r['types']:
for c in r['categories']:
output = ("Type:label:", t.get('label'), "Category:label:", c.get('label'))
I am not sure what you want to do,
but I think this may help you:
files = os.listdir('C:/Users/123456/Desktop/Ten sample /Ten sample ')# path_to_json
for FILE in files:
if FILE.endswith('.json'):
with open(FILE) as json_data:
data = json.load(json_data)
for r in (data['elements']): #print(r['types'], r['categories'])
for t in r['types']:
for c in r['categories']:
output = ("Type:label:", t.get('label'), "Category:label:", c.get('label'))
new_file_name = FILE[:-5] + '.txt'
f = open(new_file_name, 'w+')
f.write(output)
f.close()

Bad file descriptor in Python 2.7

I am downloading a file with boto3 from AWS S3, it's a basic JSON file.
{
"Counter": 0,
"NumOfReset": 0,
"Highest": 0
}
I can open the JSON file, but when I go to dump it back to the same file after changing some values, I get IOError: [Errno 9] Bad file descriptor.
with open("/tmp/data.json", "rw") as fh:
data = json.load(fh)
i = data["Counter"]
i = i + 1
if i >= data["Highest"]:
data["Highest"] = i
json.dump(data, fh)
fh.close()
Am I just using the wrong file mode or am I doing this incorrectly?
Two things. Its r+ not rw, and if you want to overwrite the previous data, you need to return to the beginning of the file, using fh.seek(0). Otherwise, the changed JSON string would be appended.
with open("/tmp/data.json", "r+") as fh:
data = json.load(fh)
i = data["Counter"]
i = i + 1
if i >= data["Highest"]:
data["Highest"] = i
fh.seek(0)
json.dump(data, fh)
fh.close()
But that may overwrite the data only partially. So closing and re-opening the file with w is probably a better idea.
with open("/tmp/data.json", "r") as fh:
data = json.load(fh)
i = data["Counter"]
i = i + 1
if i >= data["Highest"]:
data["Highest"] = i
with open("/tmp/data.json", "w") as fh:
json.dump(data, fh)
fh.close()
No need to fh.close(), that's what with .. as is for.

Categories