I have the following python script (it 'converts' xml to for example json):
import xmltodict
import pprint
import json
with open('file.xml') as fd:
doc = xmltodict.parse(fd.read())
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(json.dumps(doc))
When I run the following code it will output the json code. Question is; how can I write the output to output.json instead of the output to the screen?
Thanks!
To format json with indents you can use indent argument (link to docs).
with open('file.xml', 'r') as src_file, open('file.json', 'w+') as dst_file:
doc = xmltodict.parse(src_file.read()) #read file
dst_file.write(json.dumps(doc, indent=4)) #write file
To print Json into file
with open("your_output_file.json", "w+") as f:
f.write(json.dumps(doc))
To read JSON from file
with open("your_output_file.json") as f:
d = json.load(f)
To write your dictionary dct to a file, use json.dump
with open("output.json", "w+") as f:
json.dump(dct,f)
To read your dictionary from a file, use json.load
with open("output.json", "w+") as f:
dct = json.load(f)
Combining both examples
In [8]: import json
In [9]: dct = {'a':'b','c':'d'}
In [10]: with open("output.json", "w") as f:
...: json.dump(dct,f)
...:
In [11]: with open("output.json", "r") as f:
...: print(json.load(f))
...:
...:
{'a': 'b', 'c': 'd'}
Related
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)
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.
When I export a file from python to json file it contains charecters like,
{"-": "text", "menu": {"-": "node", "id": 2244676, "prev": "[2/40] \u0d2a\u0d4d\u0d30\u0d2f\u0d4b\u0d1c\u0d15 \u0d15\u0d4d\u0d30\u0d3f\u0d2f
I used
with open('messages.json', 'w') as outfile:
json.dump(all_messages, outfile, cls=DateTimeEncoder)
in python. How to convert it to normal unicode text?
If you want the output JSON to be human-readable, use UTF-8 encoding and the ensure_ascii=False parameter:
with open('messages.json', 'w', encoding='utf8') as outfile:
json.dump(all_messages, outfile, cls=DateTimeEncoder,ensure_ascii=False)
If you just want to read the data back in again, json.load will convert it back to Unicode:
with open('messages.json', encoding='utf8') as infile:
data = json.load(infile)
Examples with simple strings:
>>> s = '[2/40] പ്രയോജക ക്രിയ'
>>> print(json.dumps(s))
"[2/40] \u0d2a\u0d4d\u0d30\u0d2f\u0d4b\u0d1c\u0d15 \u0d15\u0d4d\u0d30\u0d3f\u0d2f"
>>> print(json.dumps(s,ensure_ascii=False))
"[2/40] പ്രയോജക ക്രിയ"
>>> out = json.dumps(s)
>>> out
'"[2/40] \\u0d2a\\u0d4d\\u0d30\\u0d2f\\u0d4b\\u0d1c\\u0d15 \\u0d15\\u0d4d\\u0d30\\u0d3f\\u0d2f"'
>>> json.loads(out)
'[2/40] പ്രയോജക ക്രിയ'
I want to create a json file like this:
{"946705035":4,"946706692":4 ...}
I am taking a column that only contains Unix Timestamp and group them.
result = data['Last_Modified_Date_unixtimestamp_no_time'].value_counts()
In [21]: result.head()
Out[21]:
1508284800 131
1508716800 106
1508371200 101
1508457600 99
1508630400 96
Name: Last_Modified_Date_unixtimestamp_no_time, dtype: int64
transform to a dict
result = result.to_dict()
result
'''
{1507161600: 1,
1507852800: 1,
1508198400: 64,
1508284800: 131,
...
1535155200: 1,
1535241600: 1}
'''
import json
result = json.dumps(result)
with open('result.json', 'w') as fp:
json.dump(result, fp, indent=4)
result
this is the data structure that I expected
{"946705035":4,"946706692":4}
You're dumping the JSON twice, which causes quotes to be escaped on the second dump. (After the first json.dumps the result is only a string, so you're just dumping a string instead of a dict again)
import json
# result = json.dumps(result)
with open('result.json', 'w') as fp:
json.dump(result, fp, indent=4)
Or remove the second dump:
import json
result = json.dumps(result)
with open('result.json', 'w') as fp:
# json.dump(result, fp, indent=4)
print(result, file=fp)
data_json=df.to_json(orient='records')
parsed=json.loads(data_json)
with open('my_data.json', 'w') as f:
json.dump(parsed, f, indent=4)
First convert the dataframe to dict
response = df.to_dict(orient="records")
And then encode the response to json
json_compatible_data = jsonable_encoder(response)
This should work well.
The simplest way to solve the above problem is to play with json.dumps() and json.loads().
import json
result = json.dumps(result)
with open('result.json', 'w') as fp:
json.loads(result, fp)
E.g., I wrote some data to the file and then try to read them:
mocked_open = mock_open()
with patch('__builtin__.open', mocked_open, create=True):
with open('file', 'w') as f:
f.write('text')
with open('file', 'r') as f:
res = f.read()
But after this,res is empty. How to get written data for this file?