Check if key exists and try JSON array again using Python

I have a bunch of JSON data from Facebook posts as below:

{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}]}, "type": "status", "id": "id_7"} 

JSON data is semi-structured, and all this is not the same. Below is my code:

 import json str = '{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}]}, "type": "status", "id": "id_7"}' data = json.loads(str) post_id = data['id'] post_type = data['type'] print(post_id) print(post_type) created_time = data['created_time'] updated_time = data['updated_time'] print(created_time) print(updated_time) if data.get('application'): app_id = data['application'].get('id', 0) print(app_id) else: print('null') #if data.get('to'): #... This is the part I am not sure how to do # Since it is in the form "to": {"data":[{"id":...}]} 

I want the code to print to_id as 1543 else print 'null'

I am not sure how to do this.

Thank!

+86
json python loops
Jul 22 '14 at 22:16
source share
5 answers
 import json jsonData = """{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}]}, "type": "status", "id": "id_7"}""" def getTargetIds(jsonData): data = json.loads(jsonData) if 'to' not in data: raise ValueError("No target in given data") if 'data' not in data['to']: raise ValueError("No data for target") for dest in data['to']['data']: if 'id' not in dest: continue targetId = dest['id'] print("to_id:", targetId) 

Output:

 In [9]: getTargetIds(s) to_id: 1543 
+109
Jul 22 '14 at 22:28
source share
— -

If you only want to check if the key exists or not

 h = {'a': 1} 'b' in h # returns False 

If you want to check if there is a value for the key

 h.get('b') # returns None 

Returns the default value if the actual value is missing

 h.get('b', 'Default value') 
+63
May 12 '17 at 15:36
source share

It is recommended to create auxiliary utility methods for such things, so that whenever you need to change the attribute verification logic, it is in one place and the code is more readable for followers.

For example, create a helper method (or a JsonUtils class with static methods) in json_utils.py :

 def get_attribute(data, attribute, default_value): return data.get(attribute) or default_value 

and then use it in your project:

 from json_utils import get_attribute def my_cool_iteration_func(data): data_to = get_attribute(data, 'to', None) if not data_to: return data_to_data = get_attribute(data_to, 'data', []) for item in data_to_data: print('The id is: %s' % get_attribute(item, 'id', 'null')) 

IMPORTANT NOTE:

There is a reason why I use data.get(attribute) or default_value instead of just data.get(attribute, default_value) :

 {'my_key': None}.get('my_key', 'nothing') # returns None {'my_key': None}.get('my_key') or 'nothing' # returns 'nothing' 

In my applications, getting an attribute with the value 'null' is the same as not getting the attribute at all. If your use is different, you should change this.

+11
Oct 31 '17 at 8:00
source share
 jsonData = """{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}, {"name": "Joe Schmoe"}]}, "type": "status", "id": "id_7"}""" def getTargetIds(jsonData): data = json.loads(jsonData) for dest in data['to']['data']: print("to_id:", dest.get('id', 'null')) 

Try:

 >>> getTargetIds(jsonData) to_id: 1543 to_id: null 

Or, if you just want to skip invalid identifiers instead of printing 'null' :

 def getTargetIds(jsonData): data = json.loads(jsonData) for dest in data['to']['data']: if 'id' in to_id: print("to_id:", dest['id']) 

So:

 >>> getTargetIds(jsonData) to_id: 1543 

Of course, in real life, you probably do not want to print each identifier, but store them and do something with them, but this is another problem.

+5
Jul 22 '14 at 22:49
source share
 if "my_data" in my_json_data: print json.dumps(my_json_data["my_data"]) 
0
Apr 14 '19 at 20:34
source share



All Articles