How do i remove something from a json file in python?

The idea:
A JSON file should be loaded and the object 2-uID with its sub-items should be deleted. The edited content should be saved in the same JSON file.

The problem:
I have already tried several approaches, like this one from an SO user, but nothing has worked for me yet.
The code shown does not delete anything, but pushes the content all into one line.

The current code
Python code:

import json

with open["path/to/json"] as data_file:
    data = json.load[data_file]

for element in data:
    if '2-uID' in element:
        del element['2-uID']

with open["path/to/json", 'w'] as data_file:
    data = json.dump[data, data_file]

JSON file:

    {
    "uID": {
        "1-uID": {
            "username": "1-username",
            "pinned": true
        },
        "2-uID": {
            "username": "2-username",
            "pinned": false
        },
        "3-uID": {
            "username": "3-username",
            "pinned": false
        }
    }
}

This is how the JSON file should look like after the process:

    {
    "uID": {
        "1-uID": {
            "username": "1-username",
            "pinned": true
        },
        "3-uID": {
            "username": "3-username",
            "pinned": false
        }
    }
}

How I handled Editing, Deleting and Adding Quiz Questions in a JSON file for my Simple Quiz written in Python

As you remember in my previous post, I posted a quiz testing my friends and our friendship using the program I made in python. This time, I needed to revise the entire quiz to fit the requirements as given by our instructor.

For this article though, I will be mostly discussing about how I actually handles the Editing, Deleting and Adding of questions in my program. I had used JSON as my database. I simply wanna challenge myself into using a format that I had never used before and gain some new experience.

You may check the entire code here.

For this project, I list down my objectives for my JSON database or must haves before I actually start coding. They are as written below:

  1. Must be able to create, read and write on a JSON file. One cell in Colab to handle reading and writing codes for the JSON file.
  2. Another cell containing the delete, edit and adding of questions functions.

Let’s Code

Deciding the content of my Data

In this cell, I had decided the structure of my JSON file. As you can see, a JSON file has resemblance to a dictionary inside an array. Here, I have a Question, A, B, C, and Answer as my keys.

I will leave the explanation of JSON file to the experts. You may read about it here.

Creating and Reading the JSON file

In the image above, I am creating the JSON file using the JSON module. On the second, cell I am now reading the JSON file I had created. Then, I created a simple for loop script just to check if the contents are right in the file I made.

Adding a New Question Function

The image above shows the function I created to handle the addition of the new question. The eval[] method is used to convert the formatted string I made into a dictionary. Honestly, I think this one needs to be improved on how I convert my user input into a dictionary that I can then append to my JSON string.

Select Question function

This function handles just the selection of a particular question in the JSON string. I had created this function because I realize for my edit and delete function I needed to select a question. Instead of repeating the code inside the edit and delete function, I could just made one function to be reused by the two functions. This function made me fall in love with the great use of creating functions for things you may use repeatedly.

As you can see above, I had added an if statement and a try-except statement. They will be handling the error I might encounter if the user entered a number less than -1 and if the user entered a number that is more than the length of the JSON string. In this way, the program will still execute instead of terminate entirely.

Edit Question function

This function handles the editing of a question just in case. I had used if-elif-else statement for this function. I am thinking of another method to use that will be better but for now this is what we have that works.

Delete Function

This function simply does one thing and that is to delete an entire question in the JSON file. It will delete including the choices and answers.

You might be wondering why in every function I have above, it always end calling the game_on[] function. The reason is after every execution of the function above, I want it to return to the main function executing the whole game which is the game_on[] function.

I had learned alot from this quiz exercise and actually discovered how useful creating functions are in a project since you can reuse them again and again. I still need to work on some adjustments for this project. Maybe adjust some codes to make it more efficient. Anyway, this ends my article. Till the next time!

How do you remove an element from a JSON file?

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

How do I remove a property from a JSON object?

JavaScript | Remove a JSON attribute..
This keyword deletes both the value of the property and the property itself..
After deletion, the property is not available for use before it is added back again..
This operator is created to be used on object properties, not on variables or functions..

How do I delete a line in json?

You really should load your json with json. load[], filter and then json. dump[] it. ... .
The initial code which you presented would work for normal text file, just replace line. strip[] with line. startswith['sometext']. ... .
I solved it with that way. Thanks for all help. ^^.

How do you remove an item from a list in Python?

How to Remove an Element from a List Using the remove[] Method in Python. To remove an element from a list using the remove[] method, specify the value of that element and pass it as an argument to the method. remove[] will search the list to find it and remove it.

Chủ Đề