15

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
arglee
  • 1,374
  • 4
  • 17
  • 30

5 Answers5

28

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).

mdml
  • 22,442
  • 8
  • 58
  • 66
  • its not working. when i ran it it did not popped off the mark from list – arglee Oct 05 '13 at 21:35
  • 1
    Hmm I ran that script with your exact input and the mark was removed. The script is outputting to a new file called `'updated-file.json'`, so it's not updating the original file. Maybe that's what's going on? – mdml Oct 05 '13 at 21:44
  • i actually paste same code of yours but it still not working. it is producing the same file as previous – arglee Oct 05 '13 at 21:52
  • As a side note, keep in mind that you can't iterate over ```obj``` with a ```for x in obj```, as you're modifying the ```obj``` per se. – alexandernst Feb 24 '14 at 10:30
  • 1
    Just for information: xrange no longer exists in python 3. – yuv Mar 27 '21 at 06:53
10

The proper way to json is to deserialize it, modify the created objects, and then, if needed, serialize them back to json. To do so, use the json module. In short, use <deserialized object> = json.loads(<some json string>) for reading json and <json output> = json.dumps(<your object>) to create json strings. In your example this would be:

import json
o = json.loads("""[
    {
        "ename": "mark",
        "url": "Lennon.com"
    },
    {
        "ename": "egg",
        "url": "Lennon.com"
    }
]""")
# kick out the unwanted item from the list
o = filter(lambda x: x['ename']!="mark", o)
output_string = json.dumps(o)
LeuX
  • 148
  • 5
2

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))
martineau
  • 119,623
  • 25
  • 170
  • 301
0

You have a list there with two items, which happen to be dictionaries. To remove the first, you can use list.remove(item) or list.pop(0) or del list[0].

http://docs.python.org/2/tutorial/datastructures.html#more-on-lists

Ivo
  • 5,378
  • 2
  • 18
  • 18
  • @lvo thanx but list.remove(0) will remove the first item from the list. i want to delete whole object from there. – arglee Oct 05 '13 at 18:42
  • 1
    @user2511142 then you're trying to work with a file, rather than a json-decoded object. call `json.load()` on it first. I also added a remove example to my code here: http://ideone.com/zQphUC – Ivo Oct 05 '13 at 19:07
  • @lvo yes i am working with file but i am using the whole thing on cmd then is shows as it deleted the data because when i use command print data[0] then it prints item next to it but json file is still not updating. – arglee Oct 05 '13 at 19:29
  • you have to save the data back with `json.dump`. It doesn't automatically "re-save" the data. – Ivo Oct 06 '13 at 03:54
0

You need to use the json module. I'm assuming python2. Try this:

import json
json_data = json.loads('<json_string>')

for i in xrange(len(json_data)):
  if(json_data[i]["id"] == "mark"):
    del json_data[i]
    break
Nikhil
  • 2,298
  • 13
  • 14
  • 3
    What if the dictionary is in a *different* position? – Martijn Pieters Oct 05 '13 at 18:38
  • @MartijnPieters Fair point. I've updated my answer to do a linear search. – Nikhil Oct 05 '13 at 18:45
  • @user2511142 You must need to decode the json. What was the error you got when you tried to decode your json text. – Nikhil Oct 05 '13 at 18:46
  • if i am using this then it is showing that TypeError: file does not support item deletion – arglee Oct 05 '13 at 18:47
  • @Nikhil i updated my question what i have tried and if i am doing in your way then also it showing Traceback (most recent call last): File "try2json.py", line 13, in del json_data[0] TypeError: 'file' object does not support item deletion – arglee Oct 05 '13 at 18:51