Reputation: 1879
Hello I am working with a json file that looks as follows:
{
"workspace_id": "car-dashboard-en",
"name": "Car Dashboard - Sample",
"created": "2017-03-20T21:24:41.498Z",
"intents": [
{
"intent": "about_VA",
"created": "2017-03-14T02:02:16.290Z",
"updated": "2017-03-14T02:02:16.290Z",
"examples": [
{
"text": "any music reccomendation?",
"created": "2017-03-14T02:02:16.290Z",
"updated": "2017-03-14T02:02:16.290Z"
},
{
"text": "can you recommend ood jazz music?",
"created": "2017-03-14T02:02:16.290Z",
"updated": "2017-03-14T02:02:16.290Z"
},
{
"text": "cloud you recommend music?",
"created": "2017-03-14T02:02:16.290Z",
"updated": "2017-03-14T02:02:16.290Z"
},
{
"text": "your name",
"created": "2017-03-14T02:02:16.290Z",
"updated": "2017-03-14T02:02:16.290Z"
}
],
"description": null
},
{
"intent": "capabilities",
"created": "2017-03-14T02:02:16.290Z",
"updated": "2017-03-14T02:02:16.290Z",
"examples": [
{
"text": "adapt to current weather condition",
"created": "2017-03-14T02:02:16.290Z",
"updated": "2017-03-14T02:02:16.290Z"
},
{
"text": "book a flight for NY on sunday",
"created": "2017-03-14T02:02:16.290Z",
"updated": "2017-03-14T02:02:16.290Z"
},
{
"text": "can you change lanes",
"created": "2017-03-14T02:02:16.290Z",
"updated": "2017-03-14T02:02:16.290Z"
},
I have one json that has a part called 'intents' this part is composed by several intents and every intent has one list of values called 'text',
I would like to extract from this file a dictionary as follows:
dictionary = {'intent_name':[text1,text1,text3,...],'intent_name2':[text1,text2,text3,...],...}
the key of this dictionary is the name of the intent associated and the values is every text of this intent,
Unfortunately I am a beginner working with json files, so I tried:
import json
with open('workspace-car-dashboard-en.json') as json_file:
data = json.load(json_file)
with the following code I am extracting and printing all the text values as follows:
for element in data['intents']:
for element2 in element['examples']:
print(element2['text'])
I got:
any music reccomendation?
can you recommend ood jazz music?
cloud you recommend music?
do you hate
Do you like
do you love
However I am not able to build the dictionary on the fly and making an append to all the text values, so I really would like to appreciate support to achieve this difficult task. I was not able to include the complete json file since it is very large so I hope this example is enough.
Upvotes: 0
Views: 34
Reputation: 5372
Create a new empty dict. Add key of each intent name and set value of an empty list. Then insert each text key value from the loop using examples text that you created.
import json
with open('workspace-car-dashboard-en.json') as json_file:
data = json.load(json_file)
new_dic = {}
for element in data['intents']:
new_dic[element['intent']] = []
for element2 in element['examples']:
new_dic[element['intent']] += [element2['text']]
Upvotes: 1