Answer the question
In order to leave comments, you need to log in
How to correctly read json file?
All the best!
I'm new to python, but in Google, somehow I couldn't find a suitable option for me, so don't judge strictly, but if you can tell me please :)
And so, I have a user_config.json file, it looks like this:
{
"userId" : "0001",
"userName": "user"
}
config = open(os.path.join(os.path.dirname(__file__), 'user_config.json'), 'r')
confid_data = json.load(config)
print confid_data
config.close()
{u'userId': u'0001', u'userName': u'user'}
Answer the question
In order to leave comments, you need to log in
Everything is correct.
u is the notation that the string is in Unicode. You are using the 2nd version of Python, there is a difference. In the third version, all strings are in Unicode, so there is no u character.
How can I remove these u' so that I can access the variable properly using the key :
confid_data.userId or confid_data.userName ?
import os
import json
config = {}
with open('user_config.json', 'r', encoding="utf-8") as cf:
config = json.loads(cf.read())
print(config) # {u'userName': u'user', u'userId': u'0001'}
print(config.get("userName")) # user
print(config.get("userName1")) # None
# но намного лучше использовать неизменяемую структуру данних
# namedtuple
from collections import namedtuple
with open('user_config.json', 'r', encoding="utf-8") as cf:
config = json.loads(cf.read(),
object_hook=lambda d: namedtuple('CONFIG', d.keys())(*d.values()))
print(config.userName, config.userId)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question