17

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
3
  • 2
    Can you show us the code you tried? Commented Oct 5, 2013 at 18:29
  • When you run this, are you having the problem because the file hasn't changed? Commented Oct 5, 2013 at 18:47
  • 1
    with open('try.json') as json_data: data = json.load(json_data) Commented Oct 5, 2013 at 19:02

5 Answers 5

29

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

Sign up to request clarification or add additional context in comments.

5 Comments

its not working. when i ran it it did not popped off the mark from list
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?
i actually paste same code of yours but it still not working. it is producing the same file as previous
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.
Just for information: xrange no longer exists in python 3.
12

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)

1 Comment

This solution is more concise
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))

Comments

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

5 Comments

What if the dictionary is in a different position?
@MartijnPieters Fair point. I've updated my answer to do a linear search.
@user2511142 You must need to decode the json. What was the error you got when you tried to decode your json text.
if i am using this then it is showing that TypeError: file does not support item deletion
@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 <module> del json_data[0] TypeError: 'file' object does not support item deletion
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

4 Comments

@lvo thanx but list.remove(0) will remove the first item from the list. i want to delete whole object from there.
@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: ideone.com/zQphUC
@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.
you have to save the data back with json.dump. It doesn't automatically "re-save" the data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.