I would like to extract the first definition value from the following json output. Additionally, it would also be nice to print all of the definition values line by line.
{
"metadata": {
"provider": "Oxford University Press"
},
"results": [
{
"id": "ace",
"language": "en",
"lexicalEntries": [
{
"entries": [
{
"etymologies": [
"Middle English (denoting the âoneâ on dice): via Old French from Latin as âunity, a unitâ"
],
"grammaticalFeatures": [
{
"text": "Singular",
"type": "Number"
}
],
"homographNumber": "100",
"senses": [
{
"definitions": [
"a playing card with a single spot on it, ranked as the highest card in its suit in most card games"
],
"domains": [
"Cards"
],
"examples": [
{
"registers": [
"figurative"
],
"text": "life had started dealing him aces again"
},
{
"text": "the ace of diamonds"
}
],
"id": "m_en_gbus0005680.006",
"short_definitions": [
"playing card with single spot on it, ranked as highest card in its suit in most card games"
]
},
{
"definitions": [
"a person who excels at a particular sport or other activity"
],
"domains": [
"Sport"
],
"examples": [
{
"text": "a motorcycle ace"
}
],
"id": "m_en_gbus0005680.010",
"registers": [
"informal"
],
"short_definitions": [
"person who excels at particular sport or other activity"
],
"subsenses": [
{
"definitions": [
"a pilot who has shot down many enemy aircraft"
],
"domains": [
"Air Force"
],
"examples": [
{
"text": "a Battle of Britain ace"
}
],
"id": "m_en_gbus0005680.011",
"short_definitions": [
"pilot who has shot down many enemy aircraft"
]
}
],
"thesaurusLinks": [
{
"entry_id": "ace",
"sense_id": "t_en_gb0000173.001"
}
]
},
{
"definitions": [
"(in tennis and similar games) a service that an opponent is unable to return and thus wins a point"
],
"domains": [
"Tennis"
],
"examples": [
{
"text": "Nadal banged down eight aces in the set"
}
],
"id": "m_en_gbus0005680.013",
"short_definitions": [
"(in tennis and similar games) service that opponent is unable to return and thus wins point"
],
"subsenses": [
{
"definitions": [
"a hole in one"
],
"domains": [
"Golf"
],
"examples": [
{
"text": "his hole in one at the 15th was Senior's second ace as a professional"
}
],
"id": "m_en_gbus0005680.014",
"registers": [
"informal"
],
"short_definitions": [
"hole in one"
]
}
]
}
]
},
{
"etymologies": [
"early 21st century: abbreviation of asexual, with alteration of spelling on the model of ace"
],
"grammaticalFeatures": [
{
"text": "Singular",
"type": "Number"
}
],
"homographNumber": "200",
"senses": [
{
"definitions": [
"a person who has no sexual feelings or desires"
],
"domains": [
"Sex"
],
"examples": [
{
"text": "both asexual, they have managed to connect with other aces offline"
}
],
"id": "m_en_gbus1190638.004",
"short_definitions": [
"asexual person"
]
}
]
}
],
"language": "en",
"lexicalCategory": "Noun",
"pronunciations": [
{
"audioFile": "http://audio.oxforddictionaries.com/en/mp3/ace_1_gb_1_abbr.mp3",
"dialects": [
"British English"
],
"phoneticNotation": "IPA",
"phoneticSpelling": "eɪs"
}
],
"text": "ace"
},
{
"entries": [
{
"grammaticalFeatures": [
{
"text": "Positive",
"type": "Degree"
}
],
"homographNumber": "101",
"senses": [
{
"definitions": [
"very good"
],
"examples": [
{
"text": "Ace! You've done it!"
},
{
"text": "an ace swimmer"
}
],
"id": "m_en_gbus0005680.016",
"registers": [
"informal"
],
"short_definitions": [
"very good"
],
"thesaurusLinks": [
{
"entry_id": "ace",
"sense_id": "t_en_gb0000173.002"
}
]
}
]
},
{
"grammaticalFeatures": [
{
"text": "Positive",
"type": "Degree"
}
],
"homographNumber": "201",
"senses": [
{
"definitions": [
"(of a person) having no sexual feelings or desires; asexual"
],
"domains": [
"Sex"
],
"examples": [
{
"text": "I didn't realize that I was ace for a long time"
}
],
"id": "m_en_gbus1190638.006",
"short_definitions": [
"asexual"
]
}
]
}
],
"language": "en",
"lexicalCategory": "Adjective",
"pronunciations": [
{
"audioFile": "http://audio.oxforddictionaries.com/en/mp3/ace_1_gb_1_abbr.mp3",
"dialects": [
"British English"
],
"phoneticNotation": "IPA",
"phoneticSpelling": "eɪs"
}
],
"text": "ace"
},
{
"entries": [
{
"grammaticalFeatures": [
{
"text": "Transitive",
"type": "Subcategorization"
},
{
"text": "Present",
"type": "Tense"
}
],
"homographNumber": "102",
"senses": [
{
"definitions": [
"(in tennis and similar games) serve an ace against (an opponent)"
],
"domains": [
"Tennis"
],
"examples": [
{
"text": "he can ace opponents with serves of no more than 62 mph"
}
],
"id": "m_en_gbus0005680.020",
"registers": [
"informal"
],
"short_definitions": [
"(in tennis and similar games) serve ace against"
],
"subsenses": [
{
"definitions": [
"score an ace on (a hole) or with (a shot)"
],
"domains": [
"Golf"
],
"examples": [
{
"text": "there was a prize for the first player to ace the hole"
}
],
"id": "m_en_gbus0005680.026",
"short_definitions": [
"score ace on hole or with"
]
}
]
},
{
"definitions": [
"achieve high marks in (a test or exam)"
],
"examples": [
{
"text": "I aced my grammar test"
}
],
"id": "m_en_gbus0005680.028",
"regions": [
"North American"
],
"registers": [
"informal"
],
"short_definitions": [
"achieve high marks in"
],
"subsenses": [
{
"definitions": [
"outdo someone in a competitive situation"
],
"examples": [
{
"text": "the magazine won an award, acing out its rivals"
}
],
"id": "m_en_gbus0005680.029",
"notes": [
{
"text": "\"ace someone out\"",
"type": "wordFormNote"
}
],
"short_definitions": [
"outdo someone in competitive situation"
]
}
]
}
]
}
],
"language": "en",
"lexicalCategory": "Verb",
"pronunciations": [
{
"audioFile": "http://audio.oxforddictionaries.com/en/mp3/ace_1_gb_1_abbr.mp3",
"dialects": [
"British English"
],
"phoneticNotation": "IPA",
"phoneticSpelling": "eɪs"
}
],
"text": "ace"
}
],
"type": "headword",
"word": "ace"
}
]
I'm reading that output with something like this:
oxford_dict = json.loads(oxford_output)
print(oxford_dict['metadata']['provider'])
But I'm not really sure how to drill down further and grab the first definition, since it exists multiple times.
You have a multi-nested dictionary.
Try:
for i in oxford_dict["results"]:
for j in i["lexicalEntries"]:
for k in j["entries"]:
for v in k["senses"]:
print(v["definitions"])
Output:
['a playing card with a single spot on it, ranked as the highest card in its suit in most card games']
['a person who excels at a particular sport or other activity']
['(in tennis and similar games) a service that an opponent is unable to return and thus wins a point']
['a person who has no sexual feelings or desires']
['very good']
['(of a person) having no sexual feelings or desires; asexual']
['(in tennis and similar games) serve an ace against (an opponent)']
['achieve high marks in (a test or exam)']
Related
I started using Python Cubes Olap recently.
I'm trying to sum/avg a JSON postgres column, how can i do this?
my db structure:
events
id
object_type
sn_name
spectra
id
snx_wavelengths (json column)
event_id
my json:
{
"dimensions": [
{
"name": "event",
"levels": [
{
"name": "object_type",
"label": "Object Type",
"attributes": [
"object_type"
]
},
{
"name": "sn_name",
"label": "name",
"attributes": [
"sn_name"
]
}
]
},
{
"name": "spectra",
"levels": [
{
"name": "catalog_name",
"label": "Catalog Name",
"attributes": [
"catalog_name"
]
},
{
"name": "capture_date",
"label": "Capture Date",
"attributes": [
"capture_date"
]
}
]
},
{
"name": "date"
}
],
"cubes": [
{
"id": "uid",
"name": "14G31Yx98ZG8aEhFHjOWNNBmFOETg5APjZo5AiHaqog5YxLMK5",
"dimensions": [
"event",
"spectra",
"date"
],
"aggregates": [
{
"name": "event_snx_wavelengths_sum",
"function": "sum",
"measure": "event.snx_wavelengths"
},
{
"name": "record_count",
"function": "count"
}
],
"joins": [
{
"master": "14G31Yx98ZG8aEhFHjOWNNBmFOETg5APjZo5AiHaqog5YxLMK5.id",
"detail": "spectra.event_id"
},
],
"mappings": {
"event.sn_name": "sn_name",
"event.object_type": "object_type",
"spectra.catalog_name": "spectra.catalog_name",
"spectra.capture_date": "spectra.capture_date",
"event.snx_wavelengths": "spectra.snx_wavelengths",
"date": "spectra.capture_date"
},
}
]
}
I'm getting the follow error:
Unknown attribute ''event.snx_wavelengths''
Anyone can help?
I already tried use mongodb to do the sum, i didnt had success.
I have the following JSON Array. If device['name'] = 'DJ', then I want to retrieve the entire json array from event_location to sum_text, otherwise i do not want that array.
{
"results": [
{
"event_location": "San Jose",
"event_type": "Party",
"source_type": [
"COMPANY",
"CONSUM"
],
"device": [
{
"name": "DJ",
"date_order": "20210120",
"manufacturer_country": "USA"
}
],
"problems": [
"Material Rupture"
],
"zip_code": "",
"sum_text": [
{
"sum_text_key": "220229361",
"text_type_code": "Additional Manufacturer Narrative",
"text": "A REVIEW OF THE DEVICE HISTORY RECORD HAS BEEN INITIATED."
},
{
"sum_text_key": "220229362",
"text_type_code": "Description of Event or Problem",
"text": "DEVICE REPORTED RIGHT SIDE RUPTURE."
}
]
},
{
"event_location": "New York",
"event_type": "Baby Shower",
"source_type": [
"COMPANY",
"CONSUM"
],
"device": [
{
"name": "Musical Band",
"date_order": "20210120",
"manufacturer_country": "USA"
}
],
"problems": [
"Material Rupture"
],
"zip_code": "",
"sum_text": [
{
"sum_text_key": "220229361",
"text_type_code": "Additional Manufacturer Narrative",
"text": "A REVIEW OF THE DEVICE HISTORY RECORD HAS BEEN INITIATED."
},
{
"sum_text_key": "220229362",
"text_type_code": "Description of Event or Problem",
"text": "DEVICE REPORTED RIGHT SIDE RUPTURE."
}
]
},
{
"event_location": "Boston",
"event_type": "Wedding",
"source_type": [
"COMPANY",
"CONSUM"
],
"device": [
{
"name": "Soft Music Band",
"date_order": "20210120",
"manufacturer_country": "USA"
}
],
"problems": [
"Material Rupture"
],
"zip_code": "",
"sum_text": [
{
"sum_text_key": "220229361",
"text_type_code": "Additional Manufacturer Narrative",
"text": "A REVIEW OF THE DEVICE HISTORY RECORD HAS BEEN INITIATED."
},
{
"sum_text_key": "220229362",
"text_type_code": "Description of Event or Problem",
"text": "DEVICE REPORTED RIGHT SIDE RUPTURE."
}
]
}
]
}
How do I to iterate it so that I get only that particular array. Have tried to iterate it with for loop. But failing to retrieve the entire array.
This should do the trick:
json = {...data here}
for event in json['results']:
for device in event['device']:
if device["name"] == "DJ":
print(event)
In the line print(event) you can do whatever you want with the current event, append it to a list, return it, or whatever you require.
Also, note that device is a list and not a dict, so we iterate over all the devices to see if one of them matches the speficied name.
I've been struggling with the nested structure in json, how to convert to correct form
{
"id": "0c576f35-d704-4fa8-8cbb-311c6be36358",
"employee_id": null,
"creator_id": "16ca2db9-206c-4e18-891d-a00a5252dbd3",
"closed_by_id": null,
"request_number": 23,
"priority": "2",
"form_id": "urlaub-weitere-abwesenheiten",
"status": "opened",
"name": "Urlaub & weitere Abwesenheiten",
"read_by_employee": false,
"custom_status": {
"id": 15793,
"name": "In Bearbeitung HR"
},
"due_date": null,
"created_at": "2021-03-29T15:18:37.572040+02:00",
"updated_at": "2021-03-29T15:22:15.590156+02:00",
"closed_at": null,
"archived_at": null,
"attachment_count": 1,
"category": {
"id": "payroll-time-management",
"name": "Payroll, Time & Attendance"
},
"public_comment_count": 0,
"form_data": [
{
"field_id": "subcategory",
"values": [
"Time & Attendance - Manage monthly/year-end consolidation and report"
]
},
{
"field_id": "separator-2",
"values": [
null
]
},
{
"field_id": "art-der-massnahme",
"values": [
"Fortbildung"
]
},
{
"field_id": "bezeichnung-der-schulung-kurses",
"values": [
"dfgzhujiko"
]
},
{
"field_id": "startdatum",
"values": [
"2021-03-26"
]
},
{
"field_id": "enddatum",
"values": [
"2021-03-27"
]
},
{
"field_id": "freistellung",
"values": [
"nein"
]
},
{
"field_id": "mit-bildungsurlaub",
"values": [
""
]
},
{
"field_id": "kommentarfeld_fortbildung",
"values": [
""
]
},
{
"field_id": "separator",
"values": [
null
]
},
{
"field_id": "instructions",
"values": [
null
]
},
{
"field_id": "entscheidung-hr-bp",
"values": [
"Zustimmen"
]
},
{
"field_id": "kommentarfeld-hr-bp",
"values": [
"wsdfghjkmhnbgvfcdxsybvnm,"
]
},
{
"field_id": "individuelle-abstimmung",
"values": [
""
]
}
],
"form_files": [
{
"id": 30129,
"filename": "empty_background.png",
"field_id": "anhang"
}
],
"visible_by_employee": false,
"organization_ids": [],
"need_edit_by_employee": false,
"attachments": []
}
using a simple solution with pandas, dataframe
Request = pd.DataFrame.from_dict(pd.json_normalize(data), orient='columns')
it's displaying almost in its correct form:
how to split a dictionary from columns form_data i form_files, I've done a lot of research, but I'm still having a lot of trouble solving this problem, how to split form_data for columns, no rows for meta to ID
You can do something like this.
pass the dataframe and the column to the function as arguments
def explode_node(child_df, column_value):
child_df = child_df.dropna(subset=[column_value])
if isinstance(child_df[str(column_value)].iloc[0], str):
child_df[column_value] = child_df[str(column_value)].apply(ast.literal_eval)
expanded_child_df = (pd.concat({i: json_normalize(x) for i, x in child_df.pop(str(column_value)).items()}).reset_index(level=1,drop=True).join(child_df, how='right', lsuffix='_left', rsuffix='_right').reset_index(drop=True))
expanded_child_df.columns = map(str.lower, expanded_child_df.columns)
return expanded_child_df
I want to use a custom type to capture $10, $5, $20, etc values in my custom action because there's no a Schema.org-defined type for this kind of data. I add this to the json file, but it doesn't work.
This is running on raspbian.
Using google assistant SDK 1.0.1 version.
The action is made for Spanish language.
{
"locale": "es",
"manifest": {
"displayName": "Imprimir",
"invocationName": "Imprimir",
"category": "PRODUCTIVITY"
},
"actions": [
{
"name": "com.example.actions.Imprimir",
"availability": {
"deviceClasses": [
{
"assistantSdkDevice": {}
}
]
},
"intent": {
"name": "com.example.intents.Imprimir",
"parameters": [
{
"name": "cantidad",
"type": "SchemaOrg_Number"
},
{
"name": "valor",
"type": "$Valor"
}
],
"trigger": {
"queryPatterns": [
"imprimir $SchemaOrg_Number:cantidad tickets de $Valor:valor"
]
}
},
"fulfillment": {
"staticFulfillment": {
"templatedResponse": {
"items": [
{
"simpleResponse": {
"textToSpeech": "De acuerdo"
}
},
{
"deviceExecution": {
"command": "com.example.commands.Imprimir",
"params": {
"cantidad": "$cantidad",
"valor": "$valor"
}
}
}
]
}
}
}
}
],
"types": [
{
"name": "$Valor",
"entities": [
{
"key": "1$",
"synonyms": [
"1 dolar"
]
},
{
"key": "2$",
"synonyms": [
"2 dolares"
]
},
{
"key": "5$",
"synonyms": [
"5 dolares"
]
},
{
"key": "10$",
"synonyms": [
"10 dolares"
]
},
{
"key": "20$",
"synonyms": [
"20 dolares"
]
}
]
}
]
}
It doesn't show me any apparent error. This is what happend when I talk the order:
ON_END_OF_UTTERANCE
ON_END_OF_UTTERANCE
ON_RECOGNIZING_SPEECH_FINISHED:
{"text": "imprimir dos ticket de $10"}
ON_RESPONDING_STARTED:
{"is_error_response": false}
ON_RESPONDING_FINISHED
ON_CONVERSATION_TURN_FINISHED:
{"with_follow_on_turn": false}
The assistant tell me that she doesn't understant.
I'm working in a spanish gaction.
I know that my custom type is not working because the event is not captured. I'm sure the json file doesn't have errors because if I ignore the "Valor" type, replace it for $SchemaOrg_Number and omit word "dolar" the gaction works well.
I already tried with $SchemaOrg_priceCurrency, but it capture the type of currency like dollar, sol, yen, euro, etc...
Your synonyms list should include each possible combination. If your query has "$10" as the string, that needs to match as a synonym or the query would not match at all.
Here is a big piece of JSON data that I fetch in my code below:
{
"status": 200,
"offset": 0,
"limit": 10,
"count": 8,
"total": 8,
"url": "/v2/dictionaries/ldoce5/entries?headword=extra",
"results": [
{
"datasets": [
"ldoce5",
"dictionary"
],
"headword": "extra",
"homnum": 3,
"id": "cqAFDjvvYg",
"part_of_speech": "adverb",
"senses": [
{
"collocation_examples": [
{
"collocation": "one/a few etc extra",
"example": {
"audio": [
{
"type": "example",
"url": "/v2/dictionaries/assets/ldoce/exa_pron/p008-001627480.mp3"
}
],
"text": "I got a few extra in case anyone else decides to come."
}
}
],
"definition": [
"in addition to the usual things or the usual amount"
],
"examples": [
{
"audio": [
{
"type": "example",
"url": "/v2/dictionaries/assets/ldoce/exa_pron/p008-001627477.mp3"
}
],
"text": "They need to offer something extra to attract customers."
}
]
}
],
"url": "/v2/dictionaries/entries/cqAFDjvvYg"
},
{
"datasets": [
"ldoce5",
"dictionary"
],
"headword": "extra-",
"id": "cqAFDk1BDw",
"part_of_speech": "prefix",
"pronunciations": [
{
"audio": [
{
"lang": "American English",
"type": "pronunciation",
"url": "/v2/dictionaries/assets/ldoce/us_pron/extra__pre.mp3"
}
],
"ipa": "ekstrə"
}
],
"senses": [
{
"definition": [
"outside or beyond"
],
"examples": [
{
"audio": [
{
"type": "example",
"url": "/v2/dictionaries/assets/ldoce/exa_pron/p008-001832333.mp3"
}
],
"text": "extragalactic (=outside our galaxy)"
}
]
}
],
"url": "/v2/dictionaries/entries/cqAFDk1BDw"
},
{
"datasets": [
"ldoce5",
"dictionary"
],
"headword": "extra",
"homnum": 1,
"id": "cqAFDjpNZQ",
"part_of_speech": "adjective",
"pronunciations": [
{
"audio": [
{
"lang": "British English",
"type": "pronunciation",
"url": "/v2/dictionaries/assets/ldoce/gb_pron/extra_n0205.mp3"
},
{
"lang": "American English",
"type": "pronunciation",
"url": "/v2/dictionaries/assets/ldoce/us_pron/extra1.mp3"
}
],
"ipa": "ˈekstrə"
}
],
"senses": [
{
"collocation_examples": [
{
"collocation": "an extra ten minutes/three metres etc",
"example": {
"audio": [
{
"type": "example",
"url": "/v2/dictionaries/assets/ldoce/exa_pron/p008-001202489.mp3"
}
],
"text": "I asked for an extra two weeks to finish the work."
}
}
],
"definition": [
"more of something, in addition to the usual or standard amount or number"
],
"examples": [
{
"audio": [
{
"type": "example",
"url": "/v2/dictionaries/assets/ldoce/exa_pron/p008-001202484.mp3"
}
],
"text": "Could you get an extra loaf of bread?"
}
],
"gramatical_info": {
"type": "only before noun"
}
}
],
"url": "/v2/dictionaries/entries/cqAFDjpNZQ"
},
{
"datasets": [
"ldoce5",
"dictionary"
],
"headword": "extra",
"homnum": 2,
"id": "cqAFDjsQjH",
"part_of_speech": "pronoun",
"senses": [
{
"collocation_examples": [
{
"collocation": "pay/charge/cost etc extra",
"example": {
"audio": [
{
"type": "example",
"url": "/v2/dictionaries/assets/ldoce/exa_pron/p008-001202499.mp3"
}
],
"text": "I earn extra for working on Sunday."
}
}
],
"definition": [
"an amount of something, especially money, in addition to the usual, basic, or necessary amount"
],
"synonym": "more"
}
],
"url": "/v2/dictionaries/entries/cqAFDjsQjH"
},
{
"datasets": [
"ldoce5",
"dictionary"
],
"headword": "extra",
"homnum": 4,
"id": "cqAFDjyTn8",
"part_of_speech": "noun",
"senses": [
{
"definition": [
"something which is added to a basic product or service that improves it and often costs more"
],
"examples": [
{
"audio": [
{
"type": "example",
"url": "/v2/dictionaries/assets/ldoce/exa_pron/p008-001202524.mp3"
}
],
"text": "Tinted windows and a sunroof are optional extras(=something that you can choose to have or not)."
}
]
}
],
"url": "/v2/dictionaries/entries/cqAFDjyTn8"
},
{
"datasets": [
"ldoce5",
"dictionary"
],
"headword": "extra virgin",
"id": "cqAFDmV2Jw",
"part_of_speech": "adjective",
"senses": [
{
"definition": [
"extra virgin olive oil comes from olives that are pressed for the first time, and is considered to be the best quality olive oil"
]
}
],
"url": "/v2/dictionaries/entries/cqAFDmV2Jw"
},
{
"datasets": [
"ldoce5",
"dictionary"
],
"headword": "extra time",
"id": "cqAFDmGZyQ",
"part_of_speech": "noun",
"senses": [
{
"american_equivalent": "overtime",
"definition": [
"a period, usually of 30 minutes, added to the end of a football game in some competitions if neither team has won after normal time"
],
"examples": [
{
"audio": [
{
"type": "example",
"url": "/v2/dictionaries/assets/ldoce/exa_pron/p008-001627835.mp3"
}
],
"text": "The match went into extra time."
}
],
"geography": "especially British English",
"gramatical_examples": [
{
"examples": [
{
"audio": [
{
"type": "example",
"url": "/v2/dictionaries/assets/ldoce/exa_pron/p008-001627834.mp3"
}
],
"text": "Beckham scored in extra time."
}
],
"pattern": "in extra time"
}
]
}
],
"url": "/v2/dictionaries/entries/cqAFDmGZyQ"
},
{
"datasets": [
"ldoce5",
"dictionary"
],
"headword": "extra-sensory perception",
"id": "cqAFDm6ceW",
"part_of_speech": "noun",
"senses": [
{
"definition": [
"ESP"
]
}
],
"url": "/v2/dictionaries/entries/cqAFDm6ceW"
}
]
}
I want to grab and print the definitions offered in the JSON results. I don't know how to express this and am getting a 'list indices must be integers or slices, not str' error for my sense = data['senses'].
#!/usr/bin/env python
import urllib.request
import json
wp = urllib.request.urlopen("http://api.pearson.com/v2/dictionaries/ldoce5/entries?headword=extra").read().decode('utf8')
jsonData=json.loads(wp)
data=jsonData['results']
for item in data:
sense = data['senses']
print(senses['definition'])
sense is actually a list with a single element, a dictionary. The contained dictionary has your desired key-value pair.
For example:
for item in data:
sense = data['senses'][0]
print(sense['definition'])