Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to delete json object using python?

Tags:

python

json

I am using python to delete and update a JSON file generated from the data provided by user, so that only few items should be stored in the database. I want to delete a particular object from the JSON file.

My JSON file is:

[
  {
      "ename": "mark",
      "url": "Lennon.com"
  },
  {
      "ename": "egg",
      "url": "Lennon.com"
  }
]

I want to delete the JSON object with ename mark.

As I am new to python I tried to delete it by converting objects into dict but it is not working. Is there any other way to do it? i tried this one:

index=0
while index < len(data):
    next=index+1
    if(data[index]['ename']==data[next]['ename']):
        print "match found at"
        print "line %d and %d" %(next,next+1)
        del data[next]
    index +=1
like image 720
arglee Avatar asked Oct 05 '13 18:10

arglee


People also ask

How do you remove a JSON object in Python?

To remove the first, you can use list. remove(item) or list. pop(0) or del list[0] .

How do I remove an item from a JSON array in Python?

You can use the pop() method to remove an element from the array.

How do you clear an object in JSON?

To remove JSON element, use the delete keyword in JavaScript.

Can we edit JSON in Python?

Import the json library with import json. Read the JSON file in a data structure using data = json. Update the Python data structure with the new entry (e.g., a new dictionary to append to the list). Write the updated JSON data back to the JSON file using json.


2 Answers

Here's a complete example that loads the JSON file, removes the target object, and then outputs the updated JSON object to file.

#!/usr/bin/python                                                               

# Load the JSON module and use it to load your JSON file.                       
# I'm assuming that the JSON file contains a list of objects.                   
import json
obj  = json.load(open("file.json"))

# Iterate through the objects in the JSON and pop (remove)                      
# the obj once we find it.                                                      
for i in xrange(len(obj)):
    if obj[i]["ename"] == "mark":
        obj.pop(i)
        break

# Output the updated file with pretty JSON                                      
open("updated-file.json", "w").write(
    json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
)

The main point is that we find the object by iterating through the objects in the loaded list, and then pop the object off the list once we find it. If you need to remove more than one object in the list, then you should store the indices of the objects you want to remove, and then remove them all at once after you've reached the end of the for loop (you don't want to modify the list while you iterate through it).

like image 62
mdml Avatar answered Sep 21 '22 07:09

mdml


Your json file contains in a list of objects, which are dictionaries in Python. Just replace the list with a new one that doesn't have the object in it:

import json

with open('testdata.json', 'rb') as fp:
    jsondata = json.load(fp)

jsondata = [obj for obj in jsondata if obj['ename'] != 'mark']

print(json.dumps(jsondata, indent=4))
like image 41
martineau Avatar answered Sep 19 '22 07:09

martineau