How to store values in list from json in python. Example
**test.json**
{
"keyword":[
{
"name": "Shakti",
"jobRequisition": "156235",
"listofKeyWord": {
"name": "JavaScript",
"mandatory": false
}
},
{
"name": "Pavan",
"jobRequisition": "652378",
"listofKeyWord":
{
"name": "Java",
"mandatory": true
}
},
{
"name": "Manali",
"jobRequisition": "872347",
"listofKeyWord": {
"name": "Python",
"mandatory": false
}
}
]
}
--Python Code-- I want read name and mandatory elements from above json and store in
mandatory_list = []
optional_list = []
example: for 1st object
"listofKeyWord": {
"name": "JavaScript",
"mandatory": false
}
how to check if value for key mandatory is false the name JavaScript should go in optional_list variable and if mandatory is true it should go in mandatory_list variable.
Final output based on above Json:
optional_list = ['Javascript','Python']
mandatory_list = ['Java']
CodePudding user response:
You can use json library.
import json
f = open('data.json')
data = json.load(f)
then your Keyword value will be a list, so you can proceed normally as you would with a list.
Concerning your task:
mandatory_list = []
optional_list = []
for keyword in data['keyword']:
listOfKeyword = keyword['listofKeyWord']
mandatory = listOfKeyword['mandatory']
if(mandatory):
mandatory_list.append(listOfKeyword['name'])
else:
optional_list.append(listOfKeyword['name'])
And the output is:
mandatory_list ['Java']
optional_list ['JavaScript', 'Python']
Guide: https://www.geeksforgeeks.org/read-json-file-using-python/
CodePudding user response:
import json
data = {
"Name": "Dev",
"Occupation": "Engineer"
}
dict_1 = json.dumps(data)
print(dict_1)