4

I am trying to delete an element in a json file,

here is my json file:

before:

{
    "names": [
        {
            "PrevStreak": false,
            "Streak": 0,
            "name": "Brody B#3719",
            "points": 0
        },
        {
            "PrevStreak": false,
            "Streak": 0,
            "name": "XY_MAGIC#1111",
            "points": 0
        }
    ]
}

after running script:


{
    "names": [
        {
            "PrevStreak": false,
            "Streak": 0,
            "name": "Brody B#3719",
            "points": 0
        }
    ]
}

how would I do this in python? the file is stored locally and I am deciding which element to delete by the name in each element

Thanks

3
  • 1
    How are you deciding which element you want to remove? Commented Apr 6, 2022 at 10:23
  • By the name in each element Commented Apr 6, 2022 at 10:24
  • You have added the python tag, but you have added no code to your question. Commented Apr 6, 2022 at 10:25

5 Answers 5

5

You will have to read the file, convert it to python native data type (e.g. dictionary), then delete the element and save the file. In your case something like this could work:

import json

filepath = 'data.json'
with open(filepath, 'r') as fp:
    data = json.load(fp)
del data['names'][1]

with open(filepath, 'w') as fp:
    json.dump(data, fp)
Sign up to request clarification or add additional context in comments.

Comments

2

I would load the file, remove the item, and then save it again. Example:

import json
with open("filename.json") as f:
    data = json.load(f)
f.pop(data["names"][1]) # or iterate through entries to find matching name
with open("filename.json", "w") as f:
    json.dump(data, f)

1 Comment

Reading the file should be done with: data = json.load(f), and writing should be done with json.dump(data,f). I'm sure that f.write(data) will result in an error.
1

Try this:

# importing the module
import ast
  
# reading the data from the file
with open('dictionary.txt') as f:
    data = f.read()
  
print("Data type before reconstruction : ", type(data))
      
# reconstructing the data as a dictionary
a_dict = ast.literal_eval(data)

{"names":[a for a in a_dict["names"] if a.get("name") !="XY_MAGIC#1111"]}

Comments

1
import json
with open("test.json",'r') as f:
   data = json.loads(f.read())
   names=data.get('names')
   for idx,name in enumerate(names):
      if name['name']=='XY_MAGIC#1111':
         del names[idx]
         break
   print(names)

In order to read the file best approach would be using the with statement after which you could just use pythons json library and convert json string to python dict. once you get dict you can access the values and do your operations as required. you could convert it as json using json.dumps() then save it

5 Comments

Your code currently has an error. Reading the file should be done with: data = json.load(f).
@quamrana if we are directly passing file then we can use json.load but i am passing string to json.loads not file. loads accept string and load accepts file
So why pass a string to loads() when you can just pass the file to load(f)?
yes you are right. But i have a habit of using loads because most of the time i deal with string.
Yes, that's fair enough. (me too)
1

This does the right thing useing the python json module, and prettyprints the json back to the file afterwards:

import json

jsonpath = '/path/to/json/file.json'

with open(jsonpath) as file:
    j = json.loads(file.read())

names_to_remove = ['XY_MAGIC#1111']

for element in j['names']:
    if element['name'] in names_to_remove:
        j['names'].remove(element)
        
with open(jsonpath, 'w') as file:
    file.write(json.dumps(j, indent=4))

Comments

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.