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

python code open(encoding='utf8') is not working

I have a json file and I want to open (read and write) them without displaying as unicode :

json file as below :

{"A":"\u0e16"}
{"B":"\u0e39"}
{"C":"\u0e43\u0e08\u0e27"}

I tried below code but is not working (still open as encoded unicode) :

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

with open("test.json",encoding='utf8') as in_data:
    for line in in_data:
        print(line)

Expected output :

{"A":"ณ"}
{"B":"คุ"}
{"C":"ของ"}

>Solution :

The file isn’t valid JSON, but is what’s called "JSON Lines Format" where each line is valid JSON. You also need to decode the JSON line to display it properly. The json.loads() function takes a string and decodes it as JSON:

import json

with open("test.json",encoding='utf8') as in_data:
    for line in in_data:
        print(json.loads(line))

Output:

{'A': 'ถ'}
{'B': 'ู'}
{'C': 'ใจว'}
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