0

I am reading a JSON object using Python. Below is the example.

var name = jsonObj['f_name']; 

I want to define a function which can be directly called from jsonObj. Below is the pseudo code.

def get_attribute(key): if key in this return this[key] else return '' 

And then I want to use this function as shown below.

jsonObj.get_attribute('f_name') 

Let me know if this is possible. Please guide me on achieving this.

1
  • You could write a class that can be construded from the JSON data. Otherwise, python deserializes it into a dict which is meant to be used as a Map, not an object with methods Commented Mar 6, 2020 at 4:49

2 Answers 2

1

Arun answers this, but as a fallback you can also use a function or another value. For example:

import json jsonObj=json.loads('{"f_name": "peter"}') jsonObj.get('f_name') # u'peter' jsonObj.get('x_name','default') # 'default' jsonObj.get('x_name',jsonObj.get('f_name')) # or could just place it after the # `get` with an or # u'peter' 
Sign up to request clarification or add additional context in comments.

4 Comments

well explained 👍🏻👍🏻
Yes.. This helped. Is there any flavour of get which can get nested attributes as well. Like record['address']['postal_code'] ?
@NeerajKumar Yes, you could do record.get('address', {}).get('postal_code')
@David542 Thanks for helping me out. Just out of curiosity, is Python capable of providing functionality to define a function and attach it to an existing class or object. Please refer to the code in my question.
1

I think you should use get

>>> dictionary = {"message": "Hello, World!"} >>> dictionary.get("message", "") 'Hello, World!' >>> dictionary.get("test", "") '' 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.