V
V
Vitaly2016-06-24 13:57:02
Python
Vitaly, 2016-06-24 13:57:02

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"
}

Trying to open and read it with python:
config =  open(os.path.join(os.path.dirname(__file__), 'user_config.json'), 'r')
confid_data = json.load(config)
print confid_data
config.close()

here is the result :
{u'userId': u'0001', u'userName': u'user'}
How do i remove the children u' so i can access the variable normally using the key :
confid_data.userId or confid_data.userName ?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Roman Kitaev, 2016-06-24
@Scorpiored88

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 ?

You read a dictionary, and the elements of the dictionary are accessed using the [] operator or the get method.
confid_data['userId'] - throws a KeyError exception if there is no such key
confid_data.get('userId') - throws None (or whatever you pass as the second argument to the method) if there is no key.
Why confid_data?

A
Artem Gribkov, 2016-06-24
@L1Qu0R

use json.load s instead

S
sim3x, 2016-06-24
@sim3x

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)

stackoverflow.com/questions/6578986/how-to-convert...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question