0

I want to make a new array and add some specific keys and values of the json object into the new array. My code adds only the value and not the key. Can someone help me?

CourseGroupCategoriesGroups=[{'GroupId': 11799, 'Name': 'Group 1', 'Description': {'Text': '', 'Html': ''}, 'Enrollments': [264, 265, 266, 50795, 50798]}, {'GroupId': 11928, 'Name': 'Group2', 'Description': {'Text': '', 'Html': ''}, 'Enrollments': [49039, 49040, 49063, 49076, 50720, 50765, 50791]}]
GroupMembership =[]

for record in CourseGroupCategoriesGroups:
    GroupMembership.append(record['Name'])  

print(GroupMembership)
CDJB
  • 14,043
  • 5
  • 29
  • 55
Abdullah
  • 3
  • 3
  • Hi there I want to make a new array and add some specific keys and valyes of the json object in to the new array. My code adds only the value and not the key. Can someone help me ? – Abdullah Dec 04 '19 at 13:45
  • Could you provide your expected output please? – Celius Stingher Dec 04 '19 at 13:46
  • GroupMembership[{'GroupId':11799, 'Name':'Group 1'}] – Abdullah Dec 04 '19 at 13:48
  • But This is a shorten list, I have iterate through 100 items. So I want to make a new json object and add some of the information for CourseGroupCategoriesGroups and some from some other list. – Abdullah Dec 04 '19 at 13:50
  • Does this answer your question? [How to extract nested JSON data?](https://stackoverflow.com/questions/57875259/how-to-extract-nested-json-data) Check my answer where I explain in detail how to address this subject. – Celius Stingher Dec 04 '19 at 13:52

3 Answers3

1

just add the names you want before the value:

GroupMembership =[]

for record in CourseGroupCategoriesGroups:
    GroupMembership.append({"Name": record['Name']})  
Bendik Knapstad
  • 1,409
  • 1
  • 9
  • 18
1

Here is a solution:

GroupMembership =[]

for record in CourseGroupCategoriesGroups:
    GroupMembership.append({"GroupId": record["GroupId"], "Name": record["Name"]})

You could also use a list comprehension:

GroupMembership = [{"GroupId": record["GroupId"], "Name": record["Name"]} for record in CourseGroupCategoriesGroups]
Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50
0
GroupMembership.append({"Name": CourseGroupCategoriesGroups[0]['Name']})
rajvi
  • 150
  • 11