Home > Net >  JSON value is converted to unicode - python
JSON value is converted to unicode - python

Time:10-26

My current Python Appium test automation framework reads data from JSON file using the json.load()

The value "Ελλάδα" stored in JSON is converted to "Ελλάδα" when json.load() method is called.

Pleases point me to a solution were I can maintain the the actual string value "Ελλάδα"

JSON data in testdata.json

{
    "country" : {"country_name" : "Ελλάδα"}
}

JSON load in .py file

with open(file_location) as test_data_obj: 
    pytest.data = json.load(test_data_obj)

This prints out "Ελλάδα"

print(pytest.data["country"]["country_name"])

CodePudding user response:

Use with open(file_location,encoding='utf-8'). For whatever reason, your system uses Latin 1 as the default encoding instead of UTF8.

The file is fine. This page, like 99.9% of web pages is UTF8. That's why you were able to write Ελλάδα without any problem.

Python 3 strings are Unicode too. If you type "Ελλάδα" in a Python console you'll get the string back.

To get what you posted I had to decode the bytes using latin-1 :

>>> "Ελλάδα".encode('utf-8').decode('latin-1')
'Î\x95λλάδα'
  • Related