Reputation: 325
I'm trying to get a json file from here. So here is my code :
import requests
import json
headers = {
'Accept': 'application/json',
}
response = {}
data = {}
response = requests.get('http://acnhapi.com/v1/villagers/1', headers=headers)
profile = response.text
open('profile.json', 'w').write(profile)
with open('profile.json') as json_file:
data = json.load(json_file)
print(data)
When I run it, this error comes up :
Traceback (most recent call last):
File "villager.py", line 11, in <module>
open('profile.json', 'w').write(profile)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.2032.0_x64__qbz5n2kfra8p0\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 236-237: character maps to <undefined>
I don't understand why there is this error. Do you have any idea ?
Upvotes: 1
Views: 96
Reputation: 5388
This is failing due to UTF-8 character set. You can use codec
module to fix the issue.
import requests
import json
import codecs
headers = {
'Accept': 'application/json',
}
response = {}
data = {}
response = requests.get('http://acnhapi.com/v1/villagers/1', headers=headers)
profile = response.text
file = codecs.open('profile.json', "w", "utf-8")
file.write(profile)
file.close()
with codecs.open('profile.json', "r", "utf-8") as json_file:
data = json.load(json_file)
print(data)
Upvotes: 1