Home > Software engineering >  python code open(encoding='utf8') is not working
python code open(encoding='utf8') is not working

Time:12-07

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

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

Expected output :

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

CodePudding user response:

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': 'ใจว'}

CodePudding user response:

when working with json files, you have to decode them before using: first import json then:

with open("jason.json", encoding="utf-8") as in_data:
    dict_from_json = json.load(in_data)
    for k, v in dict_from_json.items():
        print(k, v)

Also, you can place the for loop outside the with open block

There is also an error in your json file if you want to decode it as is, it should be written that way:

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

as you can see here, the json file must be either a dictionary-like object or a list, you can read more about it in the docs

CodePudding user response:

You opened the file but didnt read it. To read the file you have to add

lines=in_data.readlines()

after this you can write

for line in lines:
    print(line)

Also its utf-8

CodePudding user response:

There is just a small error,instead of encoding='utf8' you have to use encoding='utf-8'

Hope it will resolve the issue.

  • Related