json dump not updating the file - python

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()

Related

Store data in diff. JSON files through Loop using Python

I'm using API call through which I get data in every iteration but the issue is I'm confused that how I can save data in JSON file of every iteration.
language : Python
Version : 3.9
import virustotal_python
from pprint import pprint
folder_path = 'C:/Users/E-TIME/PycharmProjects/FYP script/263 Hascodes in Txt Format'
count = 0
for file in glob.glob(os.path.join(folder_path, '*.txt')):
with open(file, 'r') as f:
lines = f.read()
l = lines.split(" ")
l = l[0].split('\n')
for file_id in range(0,3):
with virustotal_python.Virustotal(
"ab8421085f362f075cc88cb1468534253239be0bc482da052d8785d422aaabd7") as vtotal:
resp = vtotal.request(f"files/{l[file_id]}/behaviours")
data = resp.data
pprint(data)

How to convert a text file to json file?

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)

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.

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()

I want to convert base64 to json

I want to convert from base64 to json. Existing files are .jpg, and the purpose is to load multiple files in one folder and make them into one json.
import base64
import json
import os
directory = os.listdir('C:/users/user/desktop/k-means/image')
os.chdir('C:/users/user/desktop/k-means/image')
data={}
for file in directory:
open_file = open(file,'rb')
image_read = open_file.read()
image_64_encode = base64.encodestring(image_read)
data[""] = image_64_encode.decode('ascii')
with open('words.json', 'w', encoding="utf-8") as make_file:
print(json.dumps(data))
The desired output is as follows. How do I modify my code?
{"data":
"AAAAAGHLd/f39/clOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==", "label": 5}
{"data": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==", "label": 0}
You could do something like this:
import base64
import json
import os
from pprint import pprint
directory = os.listdir('C:/users/user/desktop/k-means/image')
os.chdir('C:/users/user/desktop/k-means/image')
data={}
for file in directory:
base = os.path.basename(file)
data["label"] = base
open_file = open(file,'rb')
image_read = open_file.read()
image_64_encode = base64.encodebytes(image_read)
data["data"] = image_64_encode.decode('ascii')
final_data = json.dumps(data)
final_data = json.loads(final_data)
pprint(final_data)
#output: {"data": "/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFB...", "label": "Capture.JPG"}
Note: encodestring is a deprecated alias since Python3.1, I've used encodebytes instead.
To write this final_data to a json file, you must enclose the loop inside the open function for words.json:
with open('words.json', 'w') as make_file:
for file in directory:
base = os.path.basename(file)
data["label"] = base
open_file = open(file,'rb')
image_read = open_file.read()
image_64_encode = base64.encodebytes(image_read)
data["data"] = image_64_encode.decode('ascii')
final_data = json.dumps(data)
make_file.write(final_data)

Categories