Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
955 views
in Technique[技术] by (71.8m points)

how to delete json object using python?

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...