Home > Software design >  Create JSON from specific lines of data
Create JSON from specific lines of data

Time:10-23

I have this test data that I am trying to use to create a JSON for just select items. I have the items listed and would just like to output a JSON list with select item.

What I have:

import json

  
# Data to be written

dictionary ={

  "id": "04",

  "name": "sunil",

  "department": "HR"
}

  
# Serializing json 

x= json.dumps(dictionary,indent=0)

# JSON String

y = json.loads(x)
# Goal is to print:

{

  "id": "04",

  "name": "sunil"
}

CodePudding user response:

If you don't need to save the department key you can use this:

del y['department']

Then your y variable will print what you wanted:

{"id": "04", "name": "sunil"}

Other ways to solve the same issue

CodePudding user response:

for key in list(y.keys()):
#add all potential keys you want to remain in the final dictionary
if key == "id" or key == "name":
   continue
else:
   del y[key]

However, iterating over a dictionary is pretty slow. You could assign values to temporary variables and then remake the dictionary like this:

temp_id = y['id']
temp_name = y['name']
y.clear()
y['id'] = temp_id
y['name'] = temp_name

This should be faster that iterating over a dictionary.

  • Related