python - parse multilevel json to string with condition -


i have nested json item want flatten out comma separated string (i.e. parkinson:5, billy mays:4)so can store in database if needed future analysis. wrote out function below wondering if there's more elegant way using list comprehension (or else). found post i'm not sure how adapt needs (python - parse json values multilevel keys).

data looks this:

{'persons':      [{'name': 'parkinson', 'sentiment': '5'},       {'name': 'knott david', 'sentiment': 'none'},       {'name': 'billy mays', 'sentiment': '4'}],  'organizations':       [{'name': 'piper jaffray companies', 'sentiment': 'none'},        {'name': 'marketbeat.com', 'sentiment': 'none'},        {'name': 'zacks investment research', 'sentiment': 'none'}]  'locations': [] } 

here's code:

def parse_entities(data):     results = ''     category in data.keys():     # c_id, category in enumerate(data.keys()):         entity_data = data[category]         e_id, entity in enumerate(entity_data):             if not entity_data[e_id]['sentiment'] == 'none':                 results = results + (data[category][e_id]['name'] + ":" +                                      data[category][e_id]['sentiment'] + ",")      return results 

firstly, important thing make code shorter , nicer @ use own variables. aware entity_data = data[category] , entity = entity_data[e_id]. can write entity['name'] instead of data[category][e_id]['name'].

secondly, if want like

for category in data.keys():     entity_data = data[category] 

you can make shorter , easier read changing to

for category, entity_data in data.items(): 

but don't need here, can use data.values() iterator values. when combining these improvements code looks this:

def parse_entities(data):     results = ''     entity_data in data.values():         entity in entity_data:             if entity['sentiment'] != 'none':                 results += entity['name'] + ":" + entity['sentiment'] + ","     return results 

(i have changed results = results + ... results += ... , if not entity['sentiment'] == 'none' if entity['sentiment'] != 'none', because shorter , doesn't lower readability)

when have easier make shorter , more elegant using list comprehension:

def parse_entities(data):     return ",".join([entity['name'] + ":" + entity['sentiment']                      entity_data in data.values()                      entity in entity_data                      if not entity['sentiment'] == 'none']) 

Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -