0

I have a simple file (username.json) as shown below:

{"lastname": "doe", "firstname": "john"}

I use the following code to read the file:

with open(filename) as file_obj:
    dictionary = json.load(file_obj)
    print(dictionary['firstname']) 

But when I print the dictionary value for the key "firstname" it prints nothing.

When I print the dictionary I get the following:

{u'lastname': u'doe', u'firstname': u'john'}

I know that "u" stands for unicode but for some reason I am not able to use the firstname and lastname keys.

UPDATE:

For some reason it works now!

2
  • Wait, what do you mean by not being able to use the firstname and lastname keys? Commented Nov 21, 2017 at 1:32
  • 1
    The provided code works just fine for me Commented Nov 21, 2017 at 1:33

1 Answer 1

1

json.loads converts a json object to the python equivalent.

This means it uses lists and dicts instead of arrays and objects. You are seeing the representation of the former.

doctionary["firstname"] will get you the value in first name (ie, "doe") while it's still a python object.

If you want to see json again, you'll need to pass it through json.dumps - but of course you won't be able to manipulate it as above when in that format.

Sign up to request clarification or add additional context in comments.

2 Comments

You should include that in your question then.
Having an upvoted answer to a question blocks the OP from self-deleting it. Given as they don't seem to actually have a reproducible problem, this seems a bit unfortunate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.