2014-07-22 8 views
51

ich ein Bündel von JSON-Daten von Facebook-Beiträge wie unten haben:Überprüfen Sie, ob Schlüssel vorhanden ist und wiederholen Sie die JSON-Array mit Python

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

Die JSON-Daten ist semi-strukturierten und alles ist nicht das gleiche. Unten ist mein 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":...}]} 

ich den Code wollen die to_id als 1543 else print 'null' drucken

Ich bin nicht sicher, wie dies zu tun.

Danke!

Antwort

80
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) 

Ausgang:

In [9]: getTargetIds(s) 
to_id: 1543 
+2

Warum dies explizit 'in' Kontrollen in json_utils.py

Zum Beispiel eine Hilfsmethode (oder Klasse JsonUtils mit statischen Methoden) erstellen und "erhöhen", wenn sie fehlen? Greifen Sie einfach darauf zu, ohne zu prüfen, und Sie erhalten genau das gleiche Verhalten (außer mit einem 'KeyError' anstelle eines' ValueError'). – abarnert

3
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')) 

Versuchen Sie es:

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

Oder, wenn Sie wollen einfach nur Werte überspringen ids statt Druck 'null' fehlt:

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 

Natürlich im wirklichen Leben, Sie wollen wahrscheinlich nicht zu print jede id, aber um sie zu speichern und etwas tun mit ihnen, aber das ist ein anderes Thema.

22

Wenn alles, was Sie wollen, ist zu überprüfen, ob Schlüssel oder nicht

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

existiert Wenn Sie überprüfen wollen, ob es einen Wert für die Schlüssel

ist
h.get('b') # returns None 

Return ein Standardwert, wenn Istwert fehlt

h.get('b', 'Default value') 
1

Es ist eine gute Praxis, Helfer-Dienstprogramm Methoden für solche Dinge zu schaffen, so dass, wann immer Sie müssen Ändern Sie die Logik der Attribut-Validierung, es wäre an einem Ort, und der Code wird für die Anhänger lesbarer sein.

def has_attribute(data, attribute): 
    return attribute in data and data[attribute] is not None 

und es dann in Ihrem Projekt verwenden:

from json_utils import has_attribute 

if has_attribute(data, 'to') and has_attribute(data['to'], 'data'): 
    for item in data['to']['data']: 
     if has_attribute(item, 'id'): 
      to_id = item['id'] 
     else: 
      to_id = 'null' 

     print('The id is: %s' % to_id) 
Verwandte Themen